Ezeeroc
Ezeeroc

Reputation: 178

What is a good way to call an API once every `x` amount of time?

For example fetch from the API X every 4 hours?

Should this include caching, setTimepout or something else?

Upvotes: 0

Views: 700

Answers (2)

Perchant
Perchant

Reputation: 1

This worked for me when I used it. I put it before the API call and the API call will be called only every 4 hours (14400000 milliseconds)

useEffect(() => {
const interval = setInterval(() => {
window.location.reload();
}, 14400000);
return () => clearInterval(interval);

Upvotes: 0

yoann84
yoann84

Reputation: 820

I would use react-query which make an amazing job for caching and updating data. You also got an option "refetch interval" that could do exactly what you are looking for. You could also use staletime. https://react-query.tanstack.com/

If you don't want to use another library you can simply use setTimeOut with useEffect I guess or you could also use schedule task as it as already been said

Upvotes: 3

Related Questions