Call method from another method with in same mutation

1.2k views Asked by At

I have the following code block from my nuxt state.

export const mutations = {
  logout () {
    localStorage.removeItem('userToken')
    localStorage.removeItem('expiryDate')
    localStorage.removeItem('userId')
    this.state.userId = null
    this.state.token = null
    this.state.authenticated = false
  },

  autoLogout ({dispatch},milliseconds) {
    setTimeout(() => {
      dispatch.logout()
    }, milliseconds)
  }
}

With the above code I'm getting error message of dispatch is not a function. How do I call the logout() from autologout() method

1

There are 1 answers

0
Ogulcan Tümdoğan On BEST ANSWER

The "dispatch" syntax belongs to actions in Vuex, not mutations. to call another mutation, you need to use "commit" for mutations.

You also need to call dispatch and commit functions with a string parameter for the name of the action or mutation you want to call, e.g.

commit('logout') or dispatch('fetchUserInfo')

When it comes to your main question, committing another mutation inside a mutation is against Vuex practices, and actually not possible.

Vuex mutations can take two parameters, state and payload. commit is not one of them.

These kinds of async functions should be listed under actions, especially if you're actually going to use an API call or any kind of HTTP request instead of a setTimeOut function. In your case, I would rewrite the autoLogout mutation to an action like this:

  autoLogout ({commit}, milliseconds) {
    setTimeout(() => {
      commit('logout')
    }, milliseconds)
  }

Good luck!