Refresh page automatically in react js

Advertisements

I have a react js application to show data using an Axios GET call. I want to update my data automatically by repeating the GET call, and not using a refresh button. I could add a timer to do this. I have only a post call from an external server to send on my react js app URL. Could you suggest me a workaround?

>Solution :

You can use setInterval() function in JavaScript to repeat the GET call after a specific interval.

Here you go –

useEffect(() => {
  const interval = setInterval(() => {
    axios.get(`your-url`)
      .then(res => setData(res.data))
      .catch(err => console.error(err));
  }, 5000); //set your time here. repeat every 5 seconds

  return () => clearInterval(interval);
}, []);

Leave a ReplyCancel reply