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.