Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueX - Dispatch action in a different module from an action

I would like to clear user data upon logout, so from auth module I dispatch an action which is defined in a module ride but I am getting an error:

[vuex] unknown local action type: clearUserData, global type: auth/clearUserData

This is my code:

store/modules/auth.js

export const namespaced = true

export const mutations = {
  clearAuthData(state){
    state.apiToken = null
    state.signedIn = false
  }
}

export const actions = {
  logout({ commit, dispatch }) {
    commit('clearAuthData'))
    dispatch('ride/clearUserData', { root: true })

  }
}

store/modules/ride.js

export const namespaced = true

export const state = {
  data: []
}

export const mutations = {
  CLEAR_USER_DATA(state){
    state.data = []
  }
}

export const actions = {  
  clearUserData({ commit }) {
    commit('CLEAR_USER_DATA')
  }
}

store/store.js

import * as auth from './modules/auth'
import * as ride from './modules/ride'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    loading: false
  },
  modules: {
    auth,
    ride
  }
})

What am I doing wrong?

like image 875
jedi Avatar asked Jan 26 '19 11:01

jedi


People also ask

How do you call an action from another module Vuex?

You can call another Vuex action by passing the name of that action as a string as the first argument of dispatch : const store = new Vuex. Store({ actions: { walk(context) { context. dispatch("goForward"); }, goForward(context) { // }, }, });

Can I call action from mutation Vuex?

In Vuex, actions are functions that call mutations. Actions exist because mutations must be synchronous, whereas actions can be asynchronous. You can define actions by passing a POJO as the actions property to the Vuex store constructor as shown below. To "call" an action, you should use the Store#dispatch() function.

How do I dispatch action from mutation Vuex?

Mutations can't dispatch further actions, but actions can dispatch other actions. So one option is to have an action commit the mutation then trigger the filter action. Another option, if possible, would be to have all filters be getters that just naturally react to data changes like a computed property would.


1 Answers

Your usage of dispatch() is incorrectly passing { root: true } as the 2nd argument, which is intended for the payload. Options should be 3rd:

// dispatch('ride/clearUserData', { root: true }) // FIXME: options passed as payload
dispatch('ride/clearUserData', null, { root: true })
like image 118
tony19 Avatar answered Sep 20 '22 23:09

tony19