jeremy radcliff
jeremy radcliff

Reputation: 1109

Repeat call to React Component every 60 seconds to automatically refresh front end display

I have a React component that fetches data from a url fed by a Flask backend and displays a line graph using that data. I want to refresh the graph on the front end without the user having to manually refresh the page.

The code is:

function Graph() {
  const [graphData, setGraphData] = useState([]);

  useEffect(() => {
    fetchGraphData();
  }, []);
  
  const fetchGraphData = async () => {
    const result = await fetch("url")
    const fetchedGraphData = await result.json();

    if(res.ok) {
      setGraphData(fetchedGraphData);
    }
  };

  return (
    <div>
      <Container>
        <LineChart>
        ....
        </LineChart>
      </Container>
    </div>
  );
}

I tried using setInterval and setTimeout everywhere and any way I could think of but I can't get it to work at all.

I've gather that setTimeout should be better because it would be guaranteed to wait for a server response before executing again, as opposed to setInterval which could queue up queries in case of delays.

Upvotes: 0

Views: 4837

Answers (1)

Najmus Sakib
Najmus Sakib

Reputation: 526

Just need a timer to achieve that goal.

In your useEffect try writing this:

useEffect(() => {
const interval = setInterval(() => {
   fetchGraphData();
  },60*1000);
  return () => clearInterval(interval);
}, []);

In return all is just a cleanup function to ensure there is no timer running after unmounting the component. To know more about cleanup function https://reactjs.org/docs/hooks-effect.html#example-using-hooks-1

Upvotes: 5

Related Questions