Last active
November 13, 2020 19:37
-
-
Save djave-co/f5df078e84870a87e925cc6d4b626e3d 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
import debounce from "lodash/debounce" | |
let localStorageAvailable = () => { | |
let test = 'test'; | |
try { | |
localStorage.setItem(test, test); | |
localStorage.removeItem(test); | |
return true; | |
} catch(e) { | |
return false; | |
} | |
} | |
let debouncedUpdate = debounce((state) => { | |
localStorage.setItem('app', JSON.stringify(state)); | |
}, 200) | |
let setupLocalStorage = (store) => { | |
let previous = localStorage.getItem('app'); | |
if(previous){ | |
store.replaceState(JSON.parse(previous)); | |
} | |
} | |
const VuexLocalStorage = (store) => { | |
if( ! localStorageAvailable() ){ | |
return false; | |
} | |
setupLocalStorage(store); | |
store.subscribe((mutation, state) => { | |
debouncedUpdate(state); | |
}) | |
} | |
export default VuexLocalStorage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, I'm gonna use this as a start in the current web app I'm working on but I'm gonna port in https://github.com/gruns/irondb for the local storage persistence.