Home > Mobile >  LocalStorage expire date after midnight using moment
LocalStorage expire date after midnight using moment

Time:06-23

I'm struggling with localStorage expiry date on my app. Here's the problem:

I set a variable in local storage when user click on a button. After this button is clicked, i don't want it to be showed again after midnight of the day, for example if I click the button at 20:00, i want it to not be showed for 4 more hours.

I have this function, triggered by redux saga:

const setVarReservation = (key, value, ttl) => {
  window.localStorage.setItem('alertToBeSetted', moment().format('YYYY-MM-DD'));
};

So my variable will have key:alertToBeSetted, value: today date.

I call a saga everytime i log in the app, so i can easily do the check here. What i wanna achieve is this:

const isVarClicked = window.localStorage.getItem('alertToBeSetted');

if (isVarClicked > midnightOfThisDay) {
  window.localStorage.removeItem(alertReservationVar);
}

Is it possible to achieve this using moment? If not, can anyone show me a valid solution?

Thanks in advance

CodePudding user response:

If you set as a value the today date in the storage, i think that when you give a value to the isVarClicked, you should check if is equals to the today date or not.

Try something like this:

// `isVariable` are usually used for boolean data.
// so here you can assing a condition like this
// to check if the button was pressed today
const isVarClickedToday = localStorage.getItem('alertToBeSetted') === moment().format('YYYY-MM-DD');

if (isVarClickedToday) {
  // Hide Button
} else {
  // Show Button

  if (localStorage.getItem('alertToBeSetted')) { // True with a date, false without a value stored. (for js implicit boolean conversion)
    // If the button wasn't clicked today, but we have something in the storage, we removing it (cause it's not about today)
    localStorage.removeItem('alertToBeSetted');
  }
}

This way you are simply hiding the button when the date match today, and showing the button and resetting the localStorage (if present) when date doesn't match.

Hope this help :)

  • Related