Skip to content

Instantly share code, notes, and snippets.

@capaj
Last active March 22, 2019 18:15
Show Gist options
  • Save capaj/1eb1aeed0a483beace632dddf6ac6753 to your computer and use it in GitHub Desktop.
Save capaj/1eb1aeed0a483beace632dddf6ac6753 to your computer and use it in GitHub Desktop.
/* global localStorage */
import {observable, autorunAsync} from 'mobx'
import _ from 'lodash'
function storedObservable (key, defaultValue, debounce) {
let fromStorage = localStorage.getItem(key)
const defaultClone = _.cloneDeep(defaultValue) // we don't want to modify the given object, because userscript might want to use the original object to reset the state back to default values some time later
if (fromStorage) {
_.merge(defaultClone, JSON.parse(fromStorage))
}
const obsVal = observable(defaultClone)
autorunAsync(() => {
localStorage.setItem(key, JSON.stringify(obsVal))
}, debounce)
return obsVal
}
export default storedObservable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment