7

I'm using VUEX in my project and I need to perform some action AFTER the state changes. Here is my module on the store.js:

const state = {
    activeEvent: null
};

const mutations = {
    SET_ACTIVE_EVENT(state, activeEvent) {
        state.activeEvent = activeEvent;
    }
};

const actions = {
    setActiveEvent({ commit }, activeEvent) {
        commit("SET_ACTIVE_EVENT", activeEvent);
    }
};

export default {
    state,
    mutations,
    actions
};

Here's the code:

this.$store.dispatch("setActiveEvent", event).then(() => {
   //Something...
});

When I do this, I get this error message from console:

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

What I've tried so far:

const actions = {
    setActiveEvent({ commit }, activeEvent) {
        return new Promise(resolve => {
            commit("SET_ACTIVE_EVENT", activeEvent);

            resolve(true);
        });
    }
};

And:

const actions = {
    setActiveEvent({ commit }, activeEvent) {
        return new Promise(resolve => {
            resolve(commit("SET_ACTIVE_EVENT", activeEvent));
        });
    }
};

But both return the same error. What am I doing wrong?

Edit:

If it helps, I'm using:

  • vue ^2.5.16
  • vue-electron ^1.0.6
  • vuex ^3.0.1
  • vuex-electron ^1.0.0
  • 1
    That's odd. This behavior should work according to https://stackoverflow.com/questions/40165766/returning-promises-from-vuex-actions. Though really, it might be an antipattern. It breaks unidirectional data flow. You could add loading and error states to vuex instead and then not need the promise. – AlexMA Mar 20 '20 at 15:06
  • 2
    Calls to `dispatch` will always return a Promise, even if you don't return one explicitly yourself. That error message is probably referring to a different `then`, not the one you've posted in the question. You can check by grabbing the promise in a variable and calling `then` on that variable. e.g. `const pr = this.$store.dispatch("setActiveEvent", event); console.log(pr); pr.then(...)` – skirtle Mar 20 '20 at 15:48
  • @skirtle I have done what you suggested: `console.log(pr)` returns `undefined` and `pr.then(...)` still throws the same error – Alexandre Sottani de Carvalho Mar 20 '20 at 17:17
  • I would try updating your dependencies, at least to rule that out. Other than that the only suggestion I have is to step through to see exactly what is going on. – skirtle Mar 20 '20 at 17:50
  • did you find any solutions @AlexandreSottanideCarvalho – namila007 Apr 16 '20 at 23:13
  • Any solution found? Same issue here with vuex 3.6.0 – gcali Jan 12 '21 at 21:02

0 Answers0