Set data to localStorage with limited time to live

set-data-to-localstorage-with-limited-time-to-live

Image description

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
Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
america-makes-announces-winners-of-powder-alloy-development-for-additive-manufacturing-(padam)-project-totaling-$6m

America Makes Announces Winners of Powder Alloy Development for Additive Manufacturing (PADAM) Project Totaling $6M

Next Post
7-ways-to-identify-how-a-product-or-service-solves-customers’-problems

7 Ways to Identify How a Product or Service Solves Customers’ Problems

Related Posts