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
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')
ordispatch('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
andpayload
.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:
Good luck!