Schedule an API call in ReactJS

I have a reaction based web application that retrieves data from the Jenkins API. During the componentDidMount () function, I call the first API that starts the thread of the API call. Then I will pass the component with the data from the API.

The Jenkins server starts each project at 7.00 a.m. every day. So I want to call these React APIs every time around 8:00 PM.

Can we plan for React to call these APIs and get updated data, as previously mentioned at certain times of the day? Or refresh your browser, etc. What will lead to new API data? I'm new to React, so rate your suggestions to achieve this.

+4
source share
1 answer

API componentDidMount(). setTimeout() mount, 20:00 setInterval() 24 .

, :

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 currently earlier than 20:00
    timeLeft = execTime - currTime;
  } else {
    //it 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
}

, :

  • 20:00 .
  • 20:00 setTimeout().
  • 24 (.. 86400000 ), setInterval().

, React.

+3

Source: https://habr.com/ru/post/1692207/


All Articles