Setup the plugin and export it

Let’s make a new js file and create a plugin! Turns out its wildly easy. This is how you create a plugin:

const VuexLocalStorage = (store) => { // Plugin goes here! } export default VuexLocalStorage;

Register the Vuex plugin!

Back over in our Vuex store, we need to make sure we reference it:

import VuexLocalStorage from "./modules/VuexLocalStorage.js" const store = new Vuex.Store({

plugins: [VuexLocalStorage]

});

Check for local storage

Modernizr has a great localStorage check which I’ve used:

let localStorageAvailable = () => {

var test = 'test';

try {

localStorage.setItem(test, test);

localStorage.removeItem(test);

return true;

} catch(e) {

return false;

}

} const VuexLocalStorage = (store) => { if( ! localStorageAvailable() ){

return false;

}

...

If there is something in storage when the app loads, load it

let setupLocalStorage = (store) => {

let previous = localStorage.getItem('app'); if(previous){

store.replaceState(JSON.parse(previous));

}

} const VuexLocalStorage = (store) => { if( ! localStorageAvailable() ){

return false;

}

setupLocalStorage();

That store.replaceState replaces the state. I’ve ripped it straight from the Vuex API. If you’re going to make a plugin its a great place to start as it shows you all the methods you can call on your store in your plugin: https://vuex.vuejs.org/api/

Warning!! Don’t use the replaceState how I have here during development, as … well, if you make any changes to the structure of your state, it will be overwritten with your previous one as soon as the page loads. It needs to be wrapped in some kind of confirmation like “Load previous state?”

Side note: debouncing

I’m making an app a bit like Medium, and I don’t want to update the local storage with every single keypress. To stop this happening, we should debounce it. So I’m importing lodash and am going to do that:

import debounce from "lodash/debounce" let debouncedUpdate = debounce((state) => {

localStorage.setItem('app', JSON.stringify(state));

}, 200)

Tapping into the Vuex state

Finally we need to trigger this function. Going back to the Vuex API docs and sample plugin docs we can use store.subscribe to get every single update:

const VuexLocalStorage = (store) => { if( ! localStorageAvailable() ){

return false;

} setupLocalStorage(store); store.subscribe((mutation, state) => {

debouncedUpdate(state);

}) }

That’s all folks! You can see the whole plugin file here:

https://gist.github.com/djave-co/f5df078e84870a87e925cc6d4b626e3d