1
votes

I have a Vue component that calls a Vuex action in its create hook (an api.get that fetches some data, and then dispatches a mutation). After that mutation is completed, I need to call an action in a different store, depending on what has been set in my store's state... in this case, getUserSpecials.

I tried to use .then() on my action, but that mutation had not yet completed, even though the api.get Promise had resolved, so the store state I needed to check was not yet available.

Does anyone know if there is a 'best practice' for doing this? I also considered using a watcher on the store state.

In my component, I have:

  created () {
   this.getUserModules();
    if (this.userModules.promos.find((p) => p.type === 'specials')) {
     this.getUserSpecials();
    }
  },

methods: {
   ...mapActions('userProfile', ['getUserModules',],),
   ...mapActions('userPromos', ['getUserSpecials',],),
},

In my store I have:

const actions = {
  getUserModules ({ commit, dispatch, }) {
  api.get(/user/modules).then((response) => {
   commit('setUserModules', response);
  });
 },
};

export const mutations = {
 setUserModules (state, response) {
  Object.assign(state, response);
 },

};

Right now, the simple if check in my create hook works fine, but I'm wondering if there is a more elegant way to do this.

2

2 Answers

1
votes

[1] Your action should return a promise

getUserModules ({ commit, dispatch, }) {
  return api.get(/user/modules).then((response) => {
   commit('setUserModules', response);
  })
}

[2] Call another dispatch when the first one has been resolved

created () {
  this.getUserModules().then(response => {
    this.getUserSpecials()
  })
}
0
votes

Make your action return a promise:

Change:

      getUserModules ({ commit, dispatch, }) {
      api.get(/user/modules).then((response) => {
       commit('setUserModules', response);
      });
     },

To:

    getUserModules({commit, dispatch}) {
       return new Promise((resolve, reject) => {
            api.get(/user/modules).then((response) => {
                commit('setUserModules', response);
                resolve(response)
            }).catch((error) {
                reject(error)
            });
        });
    },

And then your created() hook can be:

      created () {
       this.getUserModules().then((response) => {
            if(response.data.promos.find((p) => p.type === 'specials'))
                this.getUserSpecials();
       }).catch((error){
        //error
       });
      },