How to trigger an action inside an action in Vuex

I am trying to create a really small Vue application with the Rails API. Therefore, at the moment I am working with Vue, Vue-Resource and Vuex. I will select all users from the database, and now I will try to update one of them. This way everything works fine (patch User), but after running the updateUser action, I want to run the fetchUsers action again to update the Vuex repository.

But when fetchUsers work inside the promise of updateUser, I get the following error:

undefined:1 Uncaught (in promise) TypeError: Cannot read property 'dispatch' of undefined 

this is what my vuex / actions.js are looking for:

 export const fetchUsers = function ({ dispatch, state }) { this.$http.get('http://localhost:3000/api/v1/users').then((response) => { dispatch('SET_USERS', response.data) }, (response) => { dispatch('SET_USERS', []) console.log(response) }) } export const updateUser = function ({ dispatch, state }, user) { this.$http.patch('http://localhost:3000/api/v1/users/' + user.id, {user: user}).then((response) => { fetchUsers() }, (response) => { console.log(response) }) } 

Now that the fetchUsers action somehow loses context (?), But I don’t know how to deal with it! Thanks for any help!

+5
source share
1 answer

this is how i got it to work :)

 import Vue from 'vue' export const fetchUsers = ({ dispatch, state }) => { Vue.http.get('http://localhost:3000/api/v1/users').then((response) => { dispatch('SET_USERS', response.data) }, (response) => { dispatch('SET_USERS', []) console.log(response) }) } export const updateUser = ({ dispatch, state }, user) => { Vue.http.patch('http://localhost:3000/api/v1/users/' + user.id, {user: user}).then((response) => { fetchUsers({dispatch}) }, (response) => { dispatch('SET_USERS', []) console.log(response) }) } 
+9
source

All Articles