polling api every x seconds with react

后端 未结 5 1947
伪装坚强ぢ
伪装坚强ぢ 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:48

    @AmitJS94, there's a detailed section on how to stop an interval that adds onto the methods that GavKilbride mentioned in this article.

    The author says to add a state for a delay variable, and to pass in "null" for that delay when you want to pause the interval:

    const [delay, setDelay] = useState(1000);
    const [isRunning, setIsRunning] = useState(true);
      useInterval(() => {
        setCount(count + 1);
      }, isRunning ? delay : null);
    
        useEffect(() => {
        function tick() {
          savedCallback.current();
        }
    
        if (delay !== null) {
          let id = setInterval(tick, delay);
          return () => clearInterval(id);
        }
      }, [delay]);
    

    Definitely read the article to get a better understanding of the details -- it's super thorough and well-written!

提交回复
热议问题