JavaScript: Update localstorage once at start of the day

Viewed 134

I need to update localstorage at start of the every day, which will contain a large value populated by an API.

Since the value is large, this needs to be done at once only, preferably at the start of the day when the application is active and then cache the value in localstorage for rest of the day.

I came across setInterval solution which will monitor the clock and will hit API at 12 AM and cache the value in the localstorage. But interval seems costly. Also, it may be possible that the application is not active/running at 12 AM on the client which can miss the API call.

Any ideas how this can be done?

1 Answers

Solution 1

supposed data is returned data from API and you want to save this data into localStorage. Then you can do..

localStorage.data = JSON.stringify({data,current_date});

Now, whenever the user visits the site, then check the current_date attribute like..

// call this function whenever users visit your site, depending on your tech stack.
const dataDate = JSON.parse(localStorage.data).current_date;
if(dataDate != today_date){
  // load the data
}

solution 2

use cookies with 1 day of expiry. I hope you know, how to use cookies.

// whenever you call API, set cookie with 1 day of expiry value
// when a user visits the site, then check if the cookie is present or not
// if the cookie is not present then load the data.
Related