Created
April 22, 2018 17:00
-
-
Save lachenmayer/f282c6c31e495e05cf83261a0052aab7 to your computer and use it in GitHub Desktop.
persist-object-property
This file contains 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
// 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