Skip to content

Instantly share code, notes, and snippets.

@mattlockyer
Last active January 14, 2021 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattlockyer/a9a04ded475cbc21421ef590e19fda0c to your computer and use it in GitHub Desktop.
Save mattlockyer/a9a04ded475cbc21421ef590e19fda0c to your computer and use it in GitHub Desktop.
Sane localStorage wrappers for JSON
export const get = (k, d = {}) => {
let v = localStorage.getItem(k)
try {
return JSON.parse(v || JSON.stringify(d))
} catch (e) {
return v
}
}
export const set = (k, v) => localStorage.setItem(k, typeof v === 'string' ? v : JSON.stringify(v))
export const del = (k) => localStorage.removeItem(k)
// e.g.
const balances = get('balances', [])
// outputs [] if never used
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment