Search code examples
javascriptvue.jsvuejs2axiosvuex

Vue store dispatch error response not being passed to UI


I'm trying to get the error response from my Vue store dispatch method, into my component, so I can tell the user if the save failed or not.

store/userDetails.js

const state = {
    loading: {
        user_details: false,
    }
}

const getters = {
    // Getters
}

const actions = {

save({commit, dispatch, rootState}, payload) {
    commit('setLoading', {name: 'users', value: true});
    axios(
        _prepareRequest('post', api_endpoints.user.details, rootState.token, payload)
    ).then((response) => {
        if (response.data) {
            commit('setState', {name: 'user_details', value: response.data.units});
            commit('setLoading', {name: 'user_details', value: false});
            dispatch(
                'CommonSettings/setSavingStatus',
                {components: {userDetails: "done"}},
                {root:true}
            );
        }
    }).catch((error)=> {
        console.log(error)
        return error
    }
    )
}

My component method

views/Users.vue

  send() {
    this.$store.dispatch({
      type: 'Users/save',
      userDetails: this.current
    }).then(response => {
      console.log(response)
    });
  },

Above, I'm logging out the response in two places.

The response in my store/userDetails.js file is logged out fine, but it's not being passed to my send() function in my component - it comes up as undefined. Any reason why it wouldn't be passed through? Is this the correct way to do this?


Solution

  • This works for me. Try this solution.
    store.js

    actions: {
        save(context, payload) {
          console.log(payload);
          return new Promise((resolve, reject) => {
            axios(url)
              .then((response) => {
                resolve(response);
              })
              .catch((error) => {
                reject(error);
              });
          });
        },
      },
    

    My Component method
    App.vue

    save(){
         this.$store.dispatch("save", dataSendToApi).then((response)=>{
           console.log(response)
         })
        }