Skip to content

Instantly share code, notes, and snippets.

@diegocardoso93
Last active March 25, 2021 21:28
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 diegocardoso93/d2aeec978f89aef3dfe203e7dddd235c to your computer and use it in GitHub Desktop.
Save diegocardoso93/d2aeec978f89aef3dfe203e7dddd235c to your computer and use it in GitHub Desktop.
simple localstorage hook abstraction
export default function usePersist(target) {
const setItem = (key, value) =>
localStorage.setItem(key, JSON.stringify(value));
const set = target
? (value) => setItem(target, value)
: (key, value) => setItem(key, value);
const getItem = (key) => JSON.parse(localStorage.getItem(key));
const get = target ? getItem(target) : (key) => getItem(key);
return [get, set];
}
@diegocardoso93
Copy link
Author

diegocardoso93 commented Mar 25, 2021

how to use

option 1:

const [pLittlePonny, psetLittlePony] = usePersist('my_little_ponny')
psetLittlePony({color: 'purple'})

option 2:

const [pget, pset] = usePersist()
pset('my_little_ponny', {color: 'purple'})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment