Schedule an API call in ReactJS Schedule an API call in ReactJS jenkins jenkins

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:

  1. Calculate the time difference between now and next 20:00 o'clock.
  2. Wait until 20:00 with setTimeout().
  3. 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.