Tutorial

Persist Vuex State with vuex-persist

Published on August 7, 2017
Default avatar

By Joshua Bemenderfer

Persist Vuex State with vuex-persist

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Vuex is great for handling state in your app, but sometimes you want it to persist across multiple pages loads and whatnot. The naive way to do this (and I’m as guilty of it as any,) is to add a quick little function call in each mutation to save the current state of your app to localStorage. Not exactly a great solution, but just not-bad-enough that it often suffices. But there’s a better way. Vuex actually has plugin support, and vuex-persist is a teeny-tiny plugin that automatically syncs your store with localStorage, or any other storage method supporting the getItem/setItem/clear interface.

Installation

Install vuex-persist in your Vue.js project.

# Yarn
$ yarn add vuex-persist
# or NPM
$ npm install vuex-persist --save

Usage

Now, wherever you initialize your store (and this may vary a lot from project to project,) import vuex-persist and initialize it as a plugin for Vuex.

main.js (Partial)
import Vue from 'vue'
import App from 'App.vue';
import Vuex 'vuex';
import VuexPersist from 'vuex-persist';


Vue.use(Vuex);

const vuexLocalStorage = new VuexPersist({
  key: 'vuex' // The key to store the state on in the storage provider.
  storage: window.localStorage, // or window.sessionStorage or localForage
  // Function that passes the state and returns the state with only the objects you want to store.
  // reducer: state => state,
  // Function that passes a mutation and lets you decide if it should update the state in localStorage.
  // filter: mutation => (true)
})

const store = new Vuex.Store({
  ...
  plugins: [vuexLocalStorage.plugin]
});

...

new Vue({
  store,
  el: '#app',
  render: h => h(App)
});

Using the reducer option.

The reducer option allows you to only store certain sections of the state. It’s a simple function that gets passed the full state tree and is expected to return an object containing only the parts of the state tree you’d like to keep. This shouldn’t, however, modify the structure of the tree, or otherwise it can’t be re-loaded.

const vuexLocalStorage = new VuexPersist({
  storage: window.localStorage, // or window.sessionStorage or localForage instance.
  // Function that passes the state and returns the state with only the objects you want to store.
  reducer: state => ({
    keepThisModule: state.keepThisModule,
    keepThisModuleToo: state.keepThisModuleToo
    // getRidOfThisModule: state.getRidOfThisModule (No one likes it.)
  })
})

Using the filter option.

Sometimes certain mutations shouldn’t trigger a store sync. For example, if you have a mutation called every few milliseconds, updating the storage every time it’s called would cause a huge degredation in performance. vuex-persist provides a filter function to address this exact use-case. You can filter out any mutations you don’t want to cause a storage update, or create a whitelist of mutations you want to keep.

const badMutations = [
  'someMutationThatGetsCalledTooOften'
]

const vuexLocalStorage = new VuexPersist({
  storage: window.localStorage, // or window.sessionStorage or localForage
  // Function that passes the state and returns the state with only the objects you want to store.
  // someMutationThatGetsCalledTooOften gets ignored
  filter: mutation => (badMutations.indexOf(mutation.type) === -1) // Boolean
})

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Joshua Bemenderfer

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

“keepThisModule” is a misleading name. One might think this store is module based. “reducer” option is for root state properties only. Use “modules” config option to whitelist actual modules.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel