How to call an API every minute for a Dashboard in REACT

后端 未结 4 1539
一整个雨季
一整个雨季 2021-02-04 03:55

I\'ve made a dashboard in React. It has no active updating, no buttons, fields or drop-downs. It will be deployed on a wall TV for viewing. All panels (9 total) are updated thro

4条回答
  •  暖寄归人
    2021-02-04 04:35

    I have seen around a lot of complications about this. No need to have it in the lifecycles or in state or promisses. In here, the service api is just a simple axios api call

    This is my full implementation as I use it with context api(omitting some private code). In my case I just care about the status response in the api since I know what I need to change. But the api can be really anything you need for/from data-wise.'

        export class MyContextApiComponent ..... {
        private timeout: ReturnType | undefined
        ...
        ...
        ...
        public statsPolling = (S_UUID: string) => {
            if (!this.timeout) {
                this.timeout = setInterval( () => { 
                    this.statsPolling(S_UUID)
                }, 3000)
            }
    
            this.state.api.StatisticsService.statsPolling(S_UUID)
                .then(res => {
                    if (res.hasDescStats) {
                        clearInterval(this.timeout)
                        
                        this.setState(prevState => ({
                            ...prevState,
                            ...
                            ...
                        }))
                    }
                })
                .catch(e => console.warn('', e))
        }
       ...
       ...
    }
    
    /// in another file in service is the api call itself with axios just checking on the server reply status
    
    export class Statistics implements IStatistics {
        public statsPolling: StatsPolling = async S_UUID => {
            return axios
                .get<{ hasDescStats: boolean }>(`/v2/api/polling?query=${S_UUID}`)
                .then(res => {
                    if (res.status === 200) {
                        return { hasDescStats: true }
                    } else {
                        return { hasDescStats: false }
                    }
                })
        }
    }
    

提交回复
热议问题