vuex empty state on logout vuex empty state on logout vue.js vue.js

vuex empty state on logout


All objects stored in Vue act as an observable. So if the reference of a value is changed/mutated it triggers the actual value to be changed too.

So, In order to reset the state the initial store modules has to be copied as a value.

On logging out of a user, the same value has to be assigned for each module as a copy.

This can be achieved as follows:

// store.js// Initial store with modules as an objectexport const initialStoreModules = {    user,    recruitment,};export default new Vuex.Store({    /**     * Assign the modules to the store      * using lodash deepClone to avoid changing the initial store module values     */    modules: _.cloneDeep(initialStoreModules),    mutations: {        // reset default state modules by looping around the initialStoreModules        resetState(state) {        _.forOwn(initialStoreModules, (value, key) => {            state[key] = _.cloneDeep(value.state);        });        },    }});

Then call commit("resetState"); when the user logs out.


Normal Approach

If user logs in, then you can add few boolean flags to ensure that user has been loggedin/loggedout.

So initial approach would be -

this.$store.commit('insertToken', {realtoken, isLoggedIn: true})

In vuex than,

insertToken (state, payload) {  state.token = payload.realtoken  state.isLoggedIn = payload.isLoggedIn  localStorage.setItem('token', payload.realtoken)}

And when user logs out you should set all flags to false,In component -

logout () {    this.$store.commit('logOut')    this.$router.replace('/login')  }

and in vuex,

logOut (state, payload) {  state.token = null  state.isLoggedIn = false  localStorage.setItem('token', null)},

So by means of isLoggedIn and token you can tell router where to navigate by using term called Navigation Guards

Example -

const checkToken = () => {if ((localStorage.getItem('token') == null) ||  (localStorage.getItem('token') == undefined)) {  return false } else {   return true }}// Navigation guardsif (to.path === '/') { if (checkToken()) {   next() } else {  router.push('/login') }

}

This is the way I use when authentication is done by means of using token as part of interacting with Vuex.


This extension does a nice jobhttps://www.npmjs.com/package/vuex-extensions

With it installed I can just call reset in the Vuex Logout Action

logout(context) {      // do the logout stuff, such as     context.commit("setUser", {});    // On logout, clear all State, using vuex-extensions    this.reset();    // if using router, change to login page       router.replace("/login");  }