Person
Person

Reputation: 2259

Is there a way to use promise in action with this structure Vuex

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;
        }
    },

Upvotes: 1

Views: 60

Answers (1)

Julian Paolo Dayag
Julian Paolo Dayag

Reputation: 3719

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');
            });

Upvotes: 1

Related Questions