Last active
October 14, 2021 20:51
-
-
Save itsHall/3a8f5b13add4525d5eee0236bcf6138f to your computer and use it in GitHub Desktop.
Functions to handle localstorage object with expiration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function setWithExpiry(key, value, ttl) { | |
const now = new Date() | |
const item = { | |
value: value, | |
expiry: now.getTime() + ttl | |
} | |
localStorage.setItem(key, JSON.stringify(item)) | |
} | |
function getWithExpiry(key) { | |
const itemStr = localStorage.getItem(key) | |
if (!itemStr) { | |
return null | |
} | |
const item = JSON.parse(itemStr) | |
const now = new Date() | |
// compare the expiry time of the item with the current time | |
if (now.getTime() > item.expiry) { | |
// If the item is expired, delete the item from storage | |
// and return null | |
localStorage.removeItem(key) | |
return null | |
} | |
return item.value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment