Skip to content

Instantly share code, notes, and snippets.

@lostvikx
Created January 29, 2022 19:05
Show Gist options
  • Save lostvikx/dcda42d2b3cc8447f906c4db5617fdfe to your computer and use it in GitHub Desktop.
Save lostvikx/dcda42d2b3cc8447f906c4db5617fdfe to your computer and use it in GitHub Desktop.
Use local storage with expiry.
"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