Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

VueJS - Vuex with LocalStorage

Using LocalStorage with Vuex

LocalStorage allows you to persist the Vuex state across page reloads. This guide covers how to use LocalStorage with Vuex to save and retrieve the Vuex state.

Key Points:

  • LocalStorage is a web storage API that allows you to store data locally within the user's browser.
  • Integrating LocalStorage with Vuex enables you to persist the state of your application across page reloads.
  • You can use plugins or manually handle the synchronization between Vuex and LocalStorage.

Manual Integration

Saving State to LocalStorage

To save the Vuex state to LocalStorage, you can use the subscribe method to listen for mutations and store the state:


// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  }
});

// Subscribe to store mutations and save the state to LocalStorage
store.subscribe((mutation, state) => {
  localStorage.setItem('store', JSON.stringify(state));
});

export default store;
                

Loading State from LocalStorage

To load the Vuex state from LocalStorage when the application initializes, you can check for the stored state and replace the initial state:


// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const persistedState = localStorage.getItem('store') ? JSON.parse(localStorage.getItem('store')) : {};

const store = new Vuex.Store({
  state: {
    count: 0,
    ...persistedState
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  }
});

// Subscribe to store mutations and save the state to LocalStorage
store.subscribe((mutation, state) => {
  localStorage.setItem('store', JSON.stringify(state));
});

export default store;
                

Using Plugins

You can use the vuex-persistedstate plugin to simplify the process of persisting Vuex state to LocalStorage:


# Install vuex-persistedstate via npm
$ npm install vuex-persistedstate

# Install vuex-persistedstate via yarn
$ yarn add vuex-persistedstate
                

Setting Up vuex-persistedstate

After installation, set up the vuex-persistedstate plugin in your Vuex store:


// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  },
  plugins: [createPersistedState()]
});

export default store;
                

Configuration Options

The vuex-persistedstate plugin provides configuration options to control which parts of the state are persisted and how:


// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    count: 0,
    user: {
      name: '',
      email: ''
    }
  },
  mutations: {
    increment(state) {
      state.count++;
    },
    setUser(state, user) {
      state.user = user;
    }
  },
  plugins: [createPersistedState({
    paths: ['user']
  })]
});

export default store;
                

Example: Persisting User State

Here is a complete example demonstrating how to persist the user state in a VueJS application using LocalStorage:


// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    user: {
      name: '',
      email: ''
    }
  },
  mutations: {
    setUser(state, user) {
      state.user = user;
    }
  },
  plugins: [createPersistedState({
    paths: ['user']
  })]
});

export default store;

// App.vue



                

Best Practices

Follow these best practices when using LocalStorage with Vuex:

  • Store Only Necessary Data: Persist only the data that needs to survive page reloads to minimize storage usage.
  • Encrypt Sensitive Data: If you need to store sensitive data, consider encrypting it before persisting.
  • Handle Storage Limitations: Be aware of storage limitations and handle errors gracefully when storage is full.
  • Test Persistence: Test the persistence functionality thoroughly to ensure data is saved and restored correctly.
  • Use Plugins: Use plugins like vuex-persistedstate to simplify the process and improve code maintainability.

Summary

This guide provided an overview of using LocalStorage with Vuex in VueJS applications, including manual integration, using plugins, examples, and best practices. By understanding and utilizing these techniques, you can effectively persist the state of your VueJS application across page reloads.