0
votes

all!

I need to get axios Promise reject in my vue component using vuex.

I have serviceApi.js file:

export default {
  postAddService(service) {
    return axios.post('api/services', service);
  }
}

my action in vuex:

actions: {
    addService(state, service) {
        state.commit('setServiceLoadStatus', 1);

        ServicesAPI.postAddService(service)
            .then( ({data}) => {
                state.commit('setServiceLoadStatus', 2);
            })
            .catch(({response}) => {
                state.commit('setServiceLoadStatus', 2);
                console.log(response.data.message);
                return Promise.reject(response); // <= can't catch this one
            });
    }
}

and in my vue component:

methods: {
        addService() {
            this.$store.dispatch('addService', this.service)
                .then(() => {
                    this.forceLeave = true;
                    this.$router.push({name: 'services'});
                    this.$store.dispatch('snackbar/fire', {
                        text: 'New Service has been added',
                        color: 'success'
                    }).then()
                })
                .catch((err) => { // <== This never hapens 
                    this.$store.dispatch('snackbar/fire', {
                        text: err.response.data.message || err.response.data.error,
                        color: 'error'
                    }).then();
                });
}

When i use axios directly in my component all work well. I get both success and error messages. But when i work using vuex i can't get error message in component, hoever in vuex action console.log prints what i need. I'm always getting only successfull messages, even when bad things hapen on beckend. How can i handle this situation using vuex ?

1
Your actions.addService doesn't return anything. It should return the promise created by the .then().catch() chain. - Bergi
Thank you, it works now. - Evgeny

1 Answers

0
votes

Wellcome to stackoverflow. One should not want to expect anything back from an action. After calling an action. Any response should be set/saved in the state via mutations. So rather have an error property on your state. Something like this should work

actions: {
    async addService(state, service) {
        try {
            state.commit('setServiceLoadStatus', 1);
            const result = await ServicesAPI.postAddService(service);
            state.commit('setServiceLoadStatus', 2);
        } catch (error) {
            state.commit("error", "Could not add service");
            state.commit('setServiceLoadStatus', 2);
            console.log(response.data.message);
        }
    }
}

And in your component you can just have an alert that listens on your state.error

Edit: Only time you are going expect something back from an action is if you want to call other actions synchronously using async /await. In that case the result would be a Promise.