LocalStorage wrapper with expiration
because everything in this world has to expire some time
LocalStorage
is a simple and handy client-side storage, but you should avoid using it because it is synchronous and cause performance issue by blocking the main execution thread.
LocalStorage has no expiration time, data in the LocalStorage persists till the user manually deletes it.
βQuestion
In this problem, the interviewer has asked you to create a localStorage wrapper with expiration support.
// here 1000 is the expiryTime in ms
myLocalStorage.setItem('rajatexplains', '42', 1000);
myLocalStorage.getItem('rajatexplains'); // 42
After 1 sec
myLocalStorage.getItem('rajatexplains'); // null
π‘π§ Before jumping onto the churning and solution part, try solving the problem yourself. There is no point of me writing these blogs if you aren't growing alongwith learning π
π§ Churning
Okay, what basic methods do we have on localStorage.
getItem(key)
setItem(key, value)
removeItem(key)
clear()
In our wrapper myLocalStorage
, the setItem(key, value)
will change to
setItem(key, value, expiry)
.
window.myLocalStorage = {
getItem(key) {
// your code here
},
setItem(key, value, expiry) {
// your code here
},
removeItem(key) {
// your code here
},
clear() {
// your code here
}
}
One thing is for sure that removeItem
and clear
methods will work the same as they do in the original localStorage API.
π Solution
Well, for setItem
method, I will call the localStorage.setItem(key, value)
and also spin up a timer using setTimeout
, which will call removeItem after the given expiry time.
I'll keep getItem
method simple, it will just return the data calling localStorage.getItem(key)
window.myLocalStorage = {
getItem(key) {
return localStorage.getItem(key)
},
setItem(key, value, expiry) {
// if the expiry time is 0, it means there is no need to add the item
if (expiry === 0) return
localStorage.setItem(key, value)
let timer;
if(expiry) {
timer = setTimeout(()=> {
this.removeItem(key);
timer && clearTimeout(timer)
}, expiry)
}
},
removeItem(key) {
localStorage.removeItem(key)
},
clear() {
localStorage.clear()
}
}
Quite easily done, right?
Don't worry, there is no catch here. It is an accepted solution π.
Such questions are asked because they look intimidating, but aren't actually. You just need to clear your head and think it through.
π§βπ« Follow ups
- Do you think we should avoid using localStorage as much as we can? If yes, why?
- What are the other options ,should we use sessionStorage or cookies then?
- What is IndexedDB? What are the advantages that it has over localStorage and sessionStorage?
If you liked what you read π§βπ« and got to learn new things, do hit like π and subscribe π to my newsletter to get instantly notified whenever I drop in new content. And don't forget to follow π me on
Hashnode - Rajat Jain
Twitter - @rajat_codes
Instagram - @javascript_to_the_rescue
LinkedIn - Rajat Jain