Blog>
Snippets

Implementing State Persistence with Vuex and LocalStorage

Provide a code example that integrates Vuex state management with the browser's LocalStorage to maintain state after page reloads.
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

// Persisted state plugin for Vuex
const vuexLocalStorage = store => {
  // Initialize store from LocalStorage
  const persistedState = localStorage.getItem('vuex');
  if (persistedState) {
    store.replaceState(JSON.parse(persistedState));
  }

  // Subscribe to store updates
  store.subscribe((mutation, state) => {
    localStorage.setItem('vuex', JSON.stringify(state));
  });
};

// Defining the Vuex store
const store = new Vuex.Store({
  plugins: [vuexLocalStorage],
  state: {
    // ... define your state
  },
  mutations: {
    // ... define your mutations
  },
  // ... other Vuex options
});

export default store;
This code sets up a Vuex store and includes a plugin for persisting the Vuex state to LocalStorage. Upon store initialization, the state is loaded from LocalStorage, if available. All subsequent state changes are automatically saved to LocalStorage, ensuring state persistence across page reloads.