Created
January 29, 2022 19:05
-
-
Save lostvikx/dcda42d2b3cc8447f906c4db5617fdfe to your computer and use it in GitHub Desktop.
Use local storage with expiry.
This file contains hidden or 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
"use strict"; | |
// ttl = time in ms | |
const setLocalData = (key, val, ttl) => { | |
const item = { | |
data: val, | |
expiry: new Date().getTime() + ttl | |
} | |
localStorage.setItem(key, JSON.stringify(item)); | |
} | |
const getLocalData = (key) => { | |
const item = localStorage.getItem(key); | |
if (item === null) return null; | |
const { data, expiry } = JSON.parse(item); | |
if (new Date().getTime() > expiry) { | |
localStorage.removeItem(key); | |
return null; | |
} else { | |
return data; | |
} | |
} | |
export { setLocalData, getLocalData }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment