0

Anyone knows a way or method to automatically clear localstorage periodically like once a week or once a month? If there's any code references will be very helpful. Thank you very much

1 Answers1

2
  1. Add a field such as expiryDate in your local storage object
  2. Add a instruction to check that date once your application starts up
  3. Clear the local storage object if currentDate > expiryDate
function setStorage() {
  // Current date - 1 day = yesterday +
  const expiryDate = new Date().setDate(new Date().getDate() - 1); // Milliseconds
  const payload = { expiryDate, otherData: {} };
  localStorage.setItem("your-data-key", JSON.stringify(payload));
}

function checkStorage() {
  const storage = JSON.parse(localStorage.getItem("your-data-key"));
  const currentDate = new Date().getTime(); // Current date in milliseconds

  if (currentDate > storage.expiryDate) {
    console.log("YOUR STORAGE IS EXPIRED PLEASE REMOVE IT");
    // Uncomment to remove the item from localSotarage
    // localStorage.removeItem("your-data-key");
    // console.log("STORAGE REMOVED");
  }

  return storage;
}

setStorage();
checkStorage();
Firmino Changani
  • 861
  • 7
  • 11