0

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?

2 Answers 2

4

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);
}, []);
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this code and it worked. I want to query any 30 secs: is there a way to start the first call with a time = 0? I fix it by making a axios.get call at the beginning.
2

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

3 Comments

Thank you. Option 1 is very interesting. I'm totally free in the reactjs app changes and I can be notified by POST call if the data has been changed. Could you address me on an example of WebSocket?
I'm think to create a nodejs server to receive the post (notifications) and set refresh attribute, and then in react to make requests (setInterval) to check if refresh attribute
Websockets are not your "normal" HTTP requests, so you don't receive GET/POST/DELETE requests into your web app. You connect to a socket that feeds information in the form of events, you then can catch those events while connecting to the socket. I think this blog post explains it in simple terms and has a tutorial example for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.