0

I am pulling api data manually and need to check for changes instantly trying to figure the best way but my code only pulls the data once. how do I get it to pull data constantly or indefinitely

import React, {useState, useEffect} from 'react';

const Engine = () => {
  const [information, setInformation] = useState(null);
  useEffect(() => {
    fetch('http://127.0.0.1:63726')
      .then((response) => response.json())
      .then((json) => {
        setInformation(json[0]);
        console.log('You can see the info here', information);
      })

      .catch((error) => console.error(error));
  }, [information]); 
  return <></>;
};
export default Engine;

I need react to check api none stop and update the state with any changes

Jerry Seigle
  • 417
  • 4
  • 12

2 Answers2

0

You can use a .setInterval or requestAnimationFrame if you'd like

Da Mahdi03
  • 1,468
  • 1
  • 9
  • 18
0

You are probably looking for setInterval() with useEffect(). This way you can load the data from server every x seconds.

Check the similar question here React setInterval in useEffect with setTimeout delay.

EDIT: It seems that you could also run this (thanks, Dan!):

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

function useInterval(callback, delay) {
  const savedCallback = useRef();

  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}

Stefan Majiros
  • 444
  • 7
  • 11