1

I have an action which fires on form submit in component

this.$store.dispatch('registerAction', this.registerData);

Also in this component I want to show message like "Registration is successful". For that I want to listen for property in my this.$store.state registerSuccess which is false by default.

registerAction (Vuex)

  return this.api.registerUser()
       .then(response => {
          if(response.success) {
               return store.dispatch('registerSuccess');
          }
          return store.dispatch('registerFail');
       });

registerSuccess mutation sets state.registerSuccess = true; (and fail sets it to false)

Question:

How can I listen for changes to state.registerSuccess in this case? If I'm putting it in computed it returns false. Although it does change in Vuex store to true

computed: {
        registerSuccess() {
            console.log(this.$store.state.registerSuccess)
            return this.$store.state.registerSuccess;
        }
    },
gil
  • 1,318
  • 12
  • 19
Person
  • 2,190
  • 7
  • 30
  • 58
  • 1
    Check this for reference https://stackoverflow.com/questions/40165766/returning-promises-from-vuex-actions – gil Aug 15 '18 at 05:53
  • This might not be related to the answer, but why do you return the dispatches and not call it directly? – Jeremy Walters Aug 15 '18 at 07:38
  • @JeremyWalters, there are a few good reasons to want to use store actions instead of hardcoding the API calls and callback directly inside a components: a) it makes the code more reusable, in case one would like to register a user from another component let's say, or b) it is easier to debug or maintain: if something goes wrong or a refactor is needed, you only need to update the store action. – matpb Aug 15 '18 at 07:53

1 Answers1

1

You've mentioned that registerSuccess is a mutation which also means that you have put it inside the mutation property inside your store object like this:

  {
    state: {
      registerSuccess: false
    },
    mutations: {
      registerSuccess(state) {
        state.registerSuccess = true;
      }
    }
  }

In that case, you would need to use commit() to execute the registerSuccess mutation.

Your code should be:

return this.api.registerUser()
            .then(response => {
                if(response.success) {
                    return store.commit('registerSuccess');
                }
                return store.commit('registerFail');
            });
Julian Paolo Dayag
  • 3,562
  • 3
  • 20
  • 32
  • I usualy call my mutations from actions. So action `registerSuccess` looks like this for example `context.commit('REGISTER_SUCCESS', payload);` And in mutation `REGISTER_SUCCESS` a change my `state`. Sorry if my question was a bit confusing. – Person Aug 15 '18 at 08:57