Schedule an API call in ReactJS
You correctly use your API calls within componentDidMount()
. You can use setTimeout()
on mount to wait until 20:00 and and trigger that event again with setInterval()
every 24 hours after that.
So like:
componentDidMount() { const currentTime = new Date().getTime(); //current unix timestamp const execTime = new Date().setHours(20,0,0,0); //API call time = today at 20:00 let timeLeft; if(currentTime < execTime) { //it's currently earlier than 20:00 timeLeft = execTime - currTime; } else { //it's currently later than 20:00, schedule for tomorrow at 20:00 timeLeft = execTime + 86400000 - currentTime } setTimeout(function() { setInterval(function() { //your code }, 86400000); //repeat every 24h }, timeLeft); //wait until 20:00 as calculated above}
In other words, it will:
- Calculate the time difference between now and next
20:00
o'clock. - Wait until
20:00
withsetTimeout()
. - Set a trigger for exactly 24 hours (i.e 86400000 ms) to repeat the code inside
setInterval()
.
This will work no matter when you start your React app.