Save vuex state after page refresh in Vue App

Vuex helps us to manage the state in a Vue application. But the current state is lost when we refresh the page.

To solve this, we need to install an additional npm package so that we can persist (or save) the state in vuex even after the page has been refreshed.

The name of the package is vuex-persist. Internally, it uses Web Storage API i.e. LocalStorage and SessionStorage.

We can use the API directly as well but vuex integration for vuex-persist is very strong and the package is well maintained.

Steps to add vuex-persist to your Vue website –

  1. Install the npm package –
npm install --save vuex-persist 
or 
yarn add vuex-persist
  1. Setup vuex-persist alongside the store –
const vuexPersist = new VuexPersist({
    key: 'user', // unique key for saving state properties in the browser storage
    storage: window.localStorage, // select the type of storage used (eg - localStorage, sessionStorage, etc)
    reducer: (state) => ({ name: state.name, age: state.age }) // select the state properties that you want persisted 
})

In the above code, we can see that not all the state variables are saved. vuex-persist offers us the flexibility to choose the specific properties which we want saved and only persists those in the storage selected.

  1. Full code –

In store.js file

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const vuexPersist = new VuexPersist({
    key: 'user', // unique key for saving state properties in the browser storage
    storage: window.localStorage, // select the type of storage used (eg - localStorage, sessionStorage, etc)
    reducer: (state) => ({ name: state.name, age: state.age }) // select the state properties that you want persisted 
})

export default new Vuex.Store({
    state: {
        name: "Alex",
        age: "23"
    },
    plugins: [vuexPersist.plugin] // adding vuex-persist as a store plugin
})

The current state will be retained and store data can be used across components as usual.

To check whether the code has worked, we can either refresh the browser and see if the changes have been retained or we can open the console and enter –

window.localStorage

This will include all the browser stored items for the application. In this case, if we see one with the key ‘user’ then, we can confirm that vuex-persist is working properly.

Note –

Scroll to Top