Vuex how to handle api error notification?

Viewed 4739

I started working with Vuex 2 weeks ago and I realized that Vuex is very good to handle the state of the app. But, it is difficult to handle the error of API calls. When I get data from the server, I dispatch an action. When data is successfully returned, of course, everything is fine. But when an error happens, I change state, I don't know how to detect it through the state from Vuejs components to notify to the user. Could anyone give me some advice?

2 Answers

I typically have the following parts:

  • A component for displaying the notification, typically an alert or a snackbar or similar, e.g. error-notification. I use this component on a high level, directly below the root app component. This depends on your layout.
  • A property in vuex indicating the error state, typically an error object w/ error code & message, e.g. error
  • One mutation in the store for raising an error setting the error property, e.g. raiseError
  • One mutation in the store for dismissing an error clearing the error property, e.g. dismissError

Using these, you need to:

  • Display error-notification based on the error in the store: <error-notification v-if="$store.state.error :error="$store.state.error"/>
  • When an error occurs, call raiseError mutation (in your API callback): vm.$store.commit('raiseError', { code: 'ERR_FOO', msg: 'A foo error ocurred'})
  • In error-notification, call the dismissError mutation when the notification is closed.

You can also return a promise in your action so that if you call it from component you can catch the error there and display a notification as needed:

in your store:

//action
const fetch = (context) => {
    return api.fetchTodos() //api here returns a promise. You can also do new Promise(...)
        .then((response) => {
            context.commit('SET_TODOS', response);
        })

};

in vue component:

this.$store.dispatch('todos/fetch', modifiedTodo)
    .catch(error => {
        //show notification
    })
Related