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

后端 未结 4 1530
一整个雨季
一整个雨季 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:44

    Move the data fetch logic into a seperate function and invoke that function using setInterval in componentDidMount method as shown below.

      componentDidMount() {
        this.loadData()
        setInterval(this.loadData, 30000);
      }
    
      async loadData() {
         try {
            const res = await fetch('https://api.apijson.com/...');
            const blocks = await res.json();
            const dataPanelone = blocks.panelone;
            const dataPaneltwo = blocks.paneltwo;
    
            this.setState({
               panelone: dataPanelone,
               paneltwo: dataPaneltwo,
            })
        } catch (e) {
            console.log(e);
        }
      }
    

    Below is a working example

    https://codesandbox.io/s/qvzj6005w

提交回复
热议问题