1
votes

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?

3

3 Answers

1
votes

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)
     })
    }
0
votes
  1. Try returning axios call in the Store Action:
// add return
return axios(
    _prepareRequest('post', api_endpoints.user.details, rootState.token, payload)
  )
  .then()   // your stuff here
  .catch()  // your stuff here
  1. If that won't work, use Promise in the Store Action. Like this:
return new Promise((resolve, reject) => {
  return axios() // simplify for readibility reason, do your stuff here
    .then((response) => {
      //... your stuff here
      resolve(response) // add this line
    })
    .catch((error) => {
      // ... your stuff here
      reject(error) // add this line
    })
})
0
votes

you should return a promise, reference link:vue doc