Creating a persistent store you can use across components with VueX and Electron Store

Nick Gottschlich
2 min readMay 5, 2020

If you are building an Electron application, you probably want to be able to save user configuration across sessions (meaning, the user closes and opens the app and everything was how they left it). Electron Store helps you do just that.

If you are using Vue to create your app, there is a good chance you are using VueX to manage state across your app (meaning, a user clicks a login button component, and several other components can now see that the user is logged in).

This post will teach you how to marry those two so that every time you update your VueX state, it is saved in persistent storage.

This is an example of a very basic VueX store. The value count is initially set to 0, and whenever incrementCount is called by store.commit('count') the value of count is incremented by 1.

For now, if this VueX store is used in an electron app, store will be set back to 0 every time the app is opened. Let’s fix that!

Notice two key changes here.

The first is count: persistentStore.get(‘count’) || 0 . We now check the persistentStore to see if a count value exists, and if not we default to 0. This will ensure the user sees what they expect when they reopen the app (meaning, what they had before, or a default).

The second is persistentStore.set(state[‘count’], state[‘count’] + 1) . We now update the persistentStore every time a VueX mutation is called.

And it really is that simple! I recommend creating a function called something like updateStore that might look something like:

const updateStore = (state, marker, value) => {
state[marker] = value;
persistentStore.set(marker, value)
}

which can then be used in every mutation, to ensure that you never forget to update both the local VueX state and the persistentStore.

One last thing to note, if you ever need to manually clear the persistentStore, you can drop in a persistentStore.clear() at the top of the file somewhere.

Good luck with your Electron + VueX app!

--

--

Nick Gottschlich

I made https://github.com/Nick-Gottschlich/Social-Amnesia. I work for Procore, building construction management software to modernize the jobsite.