Sometimes we need to set data in browser localStorage with time to live.
Real-world example
We have an online store with the cart and liked products inside. The new castomer came to our store and without athorization has started to choose products into the cart or liked list. In that case we are going to store each product from a shopping cart in browser localStorage. But obviosly we don’t need to keep them there foreever, localStorage is not not rubber. If user doesn’t continue the purchase during next 1 month it means that potentially he/she might lose his interest to it and we can can clean those data from the localStorage.
How can we do that?
Obviosly we can’t do that simply using setTimout method🙂
Option 1. We can set data to local storage with the current and expiration date fields and the mannualy implement the function that will check every time when page is reloaded does it expired or no and remove it in case of yes.
Option 2. Is mutch eseaier. Just take the ready solution – localstorage-slim. We going to set value in localStorage with the ttl and this package will check and then remove it for us, we don’t need any extra checks.
Here is an example of vanillaJS implementation
**index.html**
Test localstorage-slim
**main.js**
ls.set(localStorageKey, JSON.stringify(ticketFieldsDropDownData), {
ttl: 604800,
}); //one week in seconds