polling api every x seconds with react

后端 未结 5 1944
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 20:25

I have to monitoring some data update info on the screen each one or two seconds. The way I figured that was using this implementation:

componentDidMount() {         


        
5条回答
  •  死守一世寂寞
    2020-12-07 21:05

    Here's a simple, full solution, that:

    • Polls every X seconds

    • Has the option of increasing the timeout each time the logic runs so you don't overload the server

    • Clears the timeouts when the end user exits the component

       //mount data
       componentDidMount() {
           //run this function to get your data for the first time
           this.getYourData();
           //use the setTimeout to poll continuously, but each time increase the timer
           this.timer = setTimeout(this.timeoutIncreaser, this.timeoutCounter);
       }
      
       //unmounting process
       componentWillUnmount() {
           this.timer = null; //clear variable
           this.timeoutIncreaser = null; //clear function that resets timer
       }
      
       //increase by timeout by certain amount each time this is ran, and call fetchData() to reload screen
       timeoutIncreaser = () => {
           this.timeoutCounter += 1000 * 2; //increase timeout by 2 seconds every time
           this.getYourData(); //this can be any function that you want ran every x seconds
           setTimeout(this.timeoutIncreaser, this.timeoutCounter);
       }
      

提交回复
热议问题