Skip to content

Instantly share code, notes, and snippets.

@lachenmayer
Created April 22, 2018 17:00
Show Gist options
  • Save lachenmayer/f282c6c31e495e05cf83261a0052aab7 to your computer and use it in GitHub Desktop.
Save lachenmayer/f282c6c31e495e05cf83261a0052aab7 to your computer and use it in GitHub Desktop.
persist-object-property
// Transparently persist an object property in localStorage.
// Usage:
// persist(state, 'backgroundColor')
// console.log(state.backgroundColor) // you can access the property on the object as usual.
// state.backgroundColor = 'red' // the value will persist across sessions.
module.exports = function persist(obj, key) {
Object.defineProperty(obj, key, {
get: () => localStorage.getItem(key),
set: value => localStorage.setItem(key, value),
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment