Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making only one module persistent with vuex-persistedstate

I need to use vuex-persistedstate to make only one of my modules to persists state through refresh of the page.

Right now, it doesn't work when I use plugins: [createPersistedState()] only inside the user module.

plugins: [createPersistedState()] works only when I use it inside the store's index.js but it make all modules persistent which is not what I want.

Please, is there a way how to configure vuex-persistedstate to work only with one module?

index.js

//import createPersistedState from 'vuex-persistedstate'
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import workout from './modules/workout'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {

  },
  getters: {

  },
  mutations: {

  },
  actions: {

  },
  modules: {
    user,
    workout
  },
  //This makes all store modules persist through page refresh
  //plugins: [createPersistedState()]
})
user.js

import { USER } from '../mutation-types'
import createPersistedState from 'vuex-persistedstate'

export default {
    namespaced: true,

    state: {
        darkMode: true
    },

    getters: {
        getDarkMode: state => () => state.darkMode
    },

    actions: {
        toggleDarkMode: ({commit}) => commit(USER.TOGGLE_DARKMODE)
    }

    mutations: {
        [USER.TOGGLE_DARKMODE]: (state) => state.darkMode = !state.darkMode
    },
    //This doesn't work
    plugins: [createPersistedState()]
}

like image 290
Ondřej Ševčík Avatar asked Mar 23 '19 22:03

Ondřej Ševčík


People also ask

What is the use of Vuex Persistedstate?

The vuex-persistedstate library is a useful library for storing Vuex state in local storage. This way, we can keep the after we refresh the page.

What is Namespacing in Vuex?

In the previous Vuex tutorial, we learned that by default, getters, actions, and mutations inside modules are registered under the global namespace, which allows multiple modules to react to the same mutation or action.

What is subscribe in Vuex?

subscribe(handler, { prepend: true }) The subscribe method will return an unsubscribe function, which should be called when the subscription is no longer needed. For example, you might subscribe to a Vuex Module and unsubscribe when you unregister the module.


1 Answers

Looking at the API docs, you will need to configure the plugin to only persist a certain subset of the store.

export default new Vuex.Store({
  plugins: [
    createPersistedState({
      paths: ['user'],
    }),
  ],
});

From the docs above:

paths <Array>: An array of any paths to partially persist the state. If no paths are given, the complete state is persisted. Paths must be specified using dot notation. If using modules, include the module name. eg: "auth.user" (default: [])

like image 73
Etheryte Avatar answered Oct 06 '22 10:10

Etheryte