Home > database >  Call function on specific time on react js app?
Call function on specific time on react js app?

Time:02-01

On my react js SPA I need to call a function (that fetches an api to refresh access token) every 5 minutes. My first thought was on App.js:

useEffect(() => {
  const interval = setInterval(() => {
    // fetch API
  }, 5*60*1000);

  return () => {
    clearInterval(interval);
  };
}, []);

Problem is: say user refreshed page, or navigated to another page before the 5 minutes, then the action to fetch the API will be postponed for another 5 minutes, and so on.

What's the best approach to achieve what I'm expecting?

  1. User logs in successfully
  2. Set "timer" to fetch the API every 5 minutes regardless pages refreshes or user navigation.

Like a synchronous API fetch

CodePudding user response:

I use node-schedule its a library you can use to schedule jobs, you might be able to schedule a job every 5 minutes of an hour so that even if the user refeshes it will still call the function at the 5th minute. For instance: I load the page at 12:53 and the job is scheduled for every 5th minute so it would call the function at 12:55. If I then refesh the page it will still schedule the job at 12:55. I'm not sure if this is what you're looking for but it might be an option.

For my program I have it setup so it calls a function every midnight.

const schedule = require('node-schedule');
schedule.scheduleJob('0 0 * * *', () => {
    updateData()
})

You can find some examples here

CodePudding user response:

you can save info about previous refresh in local storage, session storage and even cookies

  • Related