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
Asked
Active
Viewed 680 times
0
-
In other words: use session storage instead of local storage – Justinas Mar 29 '21 at 06:50
1 Answers
2
- Add a field such as
expiryDate
in your local storage object - Add a instruction to check that date once your application starts up
- 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
-
-
@NovanNoviandriSumarna I've posted the code in the answer. It's a rough implementation but it works. If it helps you, please mark my reply as an answer. Thank you ;) – Firmino Changani Mar 29 '21 at 09:32