polling api every x seconds with react

后端 未结 5 1949
伪装坚强ぢ
伪装坚强ぢ 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 20:55

    Although an old question it was the top result when I searched for React Polling and didn't have an answer that worked with Hooks.

    // utils.js
    
    import React, { useState, useEffect, useRef } from 'react';
    
    export const useInterval = (callback, delay) => {
    
      const savedCallback = useRef();
    
      useEffect(() => {
        savedCallback.current = callback;
      }, [callback]);
    
    
      useEffect(() => {
        function tick() {
          savedCallback.current();
        }
        if (delay !== null) {
          const id = setInterval(tick, delay);
          return () => clearInterval(id);
        }
      }, [delay]);
    }
    

    Source: https://overreacted.io/making-setinterval-declarative-with-react-hooks/

    You can then just import and use.

    // MyPage.js
    
    import useInterval from '../utils';
    
    const MyPage = () => {
    
      useInterval(() => {
        // put your interval code here.
      }, 1000 * 10);
    
      return 
    my page content
    ; }

提交回复
热议问题