How can I clean vuex after logout?

I have two javascript files(app.js and auth.js) in store/modules. After logout(click on button) my state is cleanning in auth.js file.

auth.js

LOGOUT: (state) => {
    state.token = '',
    state.status = null,
    state.profile = {}
}

But I’m confused how can I clean my state in app.js file ? I have it in my state in app.js file:

app.js

const state = {
    userlevels: [],
    userlevel: {},
    levels: [],
}

The easiest way is to reload the page.

You can also store state as a function, so:

// app.js
function reset () {
  return {
    ...
  }
}

export default {
  state: reset(),
  mutations: {
    reset (state) {
      Object.assign(state, reset())
    }
  }
}

From auth.js you can just commit to the root:

// auth.js
LOGOUT: (state, commit) => {
    commit('app/reset', null, { root: true })
}

I’ve typed that from memory so you may need to adjust for omissions.

Other options would be to attach event listeners to your auth driver, and commit from there.

1 Like

You could take it easy by tiny package: vuex-extensions

Check out the example on CodeSandbox

Creating Vuex.Store

import Vuex from 'vuex'
import { createStore } from 'vuex-extensions'

export default createStore(Vuex.Store, {
  plugins: []
  modules: {}
})

Store resets to initial State

// Vue Component
this.$store.reset()


// Vuex action
modules: {
  sub: {
    actions: {
      logout() {
        this.reset()
      }
    }
  }
}