Reputation: 629
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
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.
Upvotes: 2
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