Last active
March 22, 2019 18:15
-
-
Save capaj/1eb1aeed0a483beace632dddf6ac6753 to your computer and use it in GitHub Desktop.
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
/* 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