1
votes

I'm creating a chat application in Laravel 6 + Vue + Vuex. I want make a call to vuex store and get a state after a dispatch actions is complete and then I want to do some processing on that state in my vue component.

In ChatWindow component

mounted: function () {
    this.$store.dispatch('setContacts').then(() => {
        console.log('dispatch called')
        // I want to call the getter here and set one of the data property
    });
}

action.js

setContacts: (context) => {
    axios.post('/users').then(response => {
        let users = response.data;
        // consoled for testing
        console.log(users);
        context.commit('setContacts', users);
    });
}

mutators.js

setContacts: (state, users) => {
    state.contacts = users;
},

Please see the screenshot below. The then method of dispatch is running before setContacts in action.js.

image of console.logs

I need to call the getter after completing dispatch action. (which will effectively set the contacts state). Then, I want to get the contacts through getContacts getter like this.

getters.js

getContacts: (state) => {
    return state.contacts;
}

I also tried calling computed property in then in mounted and it didn't work. Also, shouldn't 'dispatch called' in mounted run after console.log of setContacts in action.js as it is in then method? Thanks!

1

1 Answers

4
votes

Maybe you could wrap axios call inside another promise.

return new Promise((resolve, reject) => {

   axios.post('/users')
     .then(response => {
        let users = response.data;
        // consoled for testing
        console.log(users);
        context.commit('setContacts', users);
        resolve('Success')
     })
     .catch(error => {
        reject(error)
     })

})

And then

this.$store.dispatch('setContacts')
   .then(() => {
       console.log('dispatch called')
       console.log('getter ', this.$store.getters.contacts)
   });

Let me know what happens. It was working for a small demo that I tried.