Home > front end >  Reset localstorage variable at specific time
Reset localstorage variable at specific time

Time:01-08

How do I reset a localStorage variable that is a boolean that tracks whether a user has completed an action that day. When the time reaches, for example, 8 am local time, it resets the boolean to false to show that the action hasn't been completed yet.

If the user has completed the action that day, the localStorage variable gets set to true and we show the countdown to 8 am.

Here are my methods that check for current time and time until 8 am.

const setActionCompleted = () => {
    var hasCompleted = true;
    localStorage.setItem("action-completed-today", JSON.stringify(hasCompleted));
}

const twoDigits = (number) => {
    return (number < 10 ? '0' : '')   number;
}

const countDown = () => {
    var reset = new Date();
    var now = new Date();
    reset.setHours(8, 0, 0);
    if(now > reset){
        reset.setDate(reset.getDate()   1);
    }

    var timeToReset = ((reset - now) / 1000);

    var hours = ~~(timeToReset / 60 / 60) % 60;
    var minutes = ~~(timeToReset / 60) % 60;
    var seconds = ~~timeToReset % 60;

    return `${twoDigits(hours)}:${twoDigits(minutes)}:${twoDigits(seconds)}`;
}

const intervalId = setInterval(() => {
  console.log(countDown());
}, 1000);

// clear interval after 10 seconds so its not running indefinitely
setTimeout(() => {clearInterval(intervalId)}, 10000);

CodePudding user response:

A couple different options here. You could expire the item periodically, and then do localStorage.removeItem(), then check your boolean on if localStorage.getItem() finds an item matching your criteria instead of changing the associated value to false. To do so, you'll want to create a custom wrapper around localStorage.setItem so that it can accept a third prop for the expiry time like:

function setWithExpiry(key, value, interval) {
  const now = new Date();
  const item = {
    value: value,
    expiry: now.getTime()   interval,
  };
  localStorage.setItem(key, JSON.stringify(item));
};

Then when you get items from localStorage, if the current time is past the item's expiry time, have it remove item by key from localStorage and return null.

function getWithExpiry(key) {
  const itemStr = localStorage.getItem(key)
  if(!itemStr) {
    return null;
  }
  const item = JSON.parse(itemStr);
  const now = new Date();
  if (now.getTime() > item.expiry) {
    localStorage.removeItem(key);
    return null;
  }
  return item.value;
}

Theoretically then you could just reset the value to false when it's found if it is expired instead of removing it though, if you want.

  •  Tags:  
  • Related