pasquy73
pasquy73

Reputation: 629

Refresh page automatically in react js

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?

Upvotes: 0

Views: 11100

Answers (2)

derFrosty
derFrosty

Reputation: 548

The way I see it, there are 3 options available to you.

Option 1: Would be to have WebSockets available in your API and connect your react app to them. Whenever the data is updated the app receives and "update" with the changes. This is the best option if you (or your team) are the devs for the backend/API.

Option 2: Having a button that redos your request would be the easy option. The user can always re-request whenever they want.

Option 3: Re-requesting from time-to-time can be achieved by using setInterval(). Which most people would not recommend unless 100% necessary. This method can be harmful for various reasons.

  • You're requesting multiple times, not sure if changes were made, wasting bandwidth and clogging your API with "useless" requests
  • If the API isn't yours, they can block your app from accessing due to multiple requests being made

Upvotes: 2

Arafat Rahman
Arafat Rahman

Reputation: 408

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);
}, []);

Upvotes: 4

Related Questions