Build your own data persist plugin for Vuex

Luis Godinho
Jun 4, 2019 · 3 min read

If you started using Vue.js in your projects like me, you’d probably got into a position where you need unrelated (not linked by parenthood) components to talk (share props) to each other.

Photo by v2osk on Unsplash

The first pattern you probably tried was the global event bus, where an empty Vue instance was created just to bridge between the components in the need to communicate.

Problem is, this pattern is simple and fine for one or two interactions between components but it gets messy as soon the application starts to become bigger. The communication logic will be scattered in several components (some emitting events, others binding to listen them), thus reducing the re-usability and the code readability.

If you’re still using the event bus pattern… stop it…now.

Although Dan Abramov says that we’ll notice when we need a Flux pattern on our app, I want to accent that Vuex (the Flux library from Vue.js suite) is really easy to pick up, and although it sounds a lot of overhead in the beginning it will pay off sooner than expected.

After some projects using Vuex, I got into a situation where I would need to keep the data state (the one stored using Vuex) even after a page refresh. The most trivial example is a shopping cart, where it would be nice if we keep the added products in the cart, even if the user leaves the page, in case he comes back.

A quick google search drove me to existent Vuex plugins (what’s a Vuex plugin?) that achieve a level of data persistence across page reloads, like vuex-persistedstate¹ and vuex-persist².

These plugins use by default the browser’s localStorage API and are fairly easy to use and configure. But, I was very concerned with the idea of keeping the entire data state in the browser when I just needed a small set of it (e.g. the shopping cart).

This is why I wrote my own data persist plugin ( persist-data.js ):

Added to my store as follows:

import persistDataPlugin from './plugins/persist-data';
const store = new Vuex.Store({
plugins: [ persistDataPlugin ],
export default store;

On line 5, is where the plugin registers (subscribes) to the store. This method runs when the store is initialized and it’s where the plugin hooks its logic.

store.subscribe((mutation, state) => {}) // line 5

The subscribe method accepts a callback which will be called after every store mutation. This is why on line 8 and 16 the plugin is testing against a mutation type (the mutation string name) to make sure it only captures the desired mutations:

  • when the cart is created (on page load)
  • when the cart is updated (add/remove product)
if( 'shop/addToCart' === mutation.type 
|| 'shop/removeFromCart' === mutation.type ) { // line 8
//...if( 'shop/initStore' === mutation.type ) {} // line 16

On my cart component I can add the following line:

created() {
this.$store.commit( 'shop/initStore' );

which will trigger the persist data plugin to check if we have a saved cart on localStorage:

storage = localStorage.getItem( 'my_site_cart' ) || false;  //19

and in case of success, it will populate the cart state on the Vuex store:

store.commit( 'shop/setCart', ); // line 26

I’ve added a timestamp to the localStorage record to make sure the cart only persists for 1 day.

Thank you for getting here! I hope this story is useful for you. Let me know in the comments if you also implemented your own persist data solution or if you are using an existent plugin.

¹ Vuex-persistedstate [github]
² Vuex-persist [github]

The Startup

Get smarter at building your thing. Join The Startup’s +725K followers.

Luis Godinho

Written by

Making web with WordPress and Vue.js. Co-founder of GOMO

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +725K followers.

Luis Godinho

Written by

Making web with WordPress and Vue.js. Co-founder of GOMO

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +725K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store