Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Schedule an API call in ReactJS

I have a react based web app which retrieves data from Jenkins APIs. During the componentDidMount() function I'm calling the first API which starts the API calling flow. Then I will render the component with the data from the API.

The Jenkins server starts building each project at 7.00am every day. Therefore I want to call these APIs from React around 8.00pm everyday.

Can we schedule React to call these APIs and get it's updated data as previously mentioned during a specific time of the day? Or refresh browser etc which results in new API data? I'm new to React so appreciate your suggestions to achieve this.

like image 539
channae Avatar asked Jan 15 '18 12:01

channae


People also ask

Can you schedule an API call?

With the APImetrics scheduler you can: Set the frequency you want to call your APIs at – this can be from once per second per location through to once a day. Select the locations you want to run from – this be refined to be a specific set of locations, or a region or a specific cloud.

How call post API in react JS?

Use Plain JavaScript to Make a POST Request in React In JavaScript, the traditional way to send any request to an API is using the XMLHttpRequest() interface. You can create an instance of this object and store it in the variable. Copy var req = new XMLHttpRequest(); req. open('POST', '/endpoint', true); req.


1 Answers

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.

like image 100
Chris Avatar answered Sep 20 '22 06:09

Chris