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.
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.
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.
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:
20:00
o'clock.20:00
with setTimeout()
.setInterval()
.This will work no matter when you start your React app.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With