Struggling a bit to set up error handling with vuex. There seems to be quite a few ways to do so and little documentation on proper error handling. I\'ve been experimenting with
Create an error
key in the state of each Vuex module. Then dispatch the error for a given component to its relative Vuex module. Then create a global handler to watch for errors in the separate Vuex modules and, if one is triggered, display the error.
// store/auth.js
export const state = () => {
return {
success: null,
error: null
}
}
export const actions = {
async login({ commit }, { email, password }) {
try {
const response = await axios.post('/api/login', {
email,
password
})
commit('SET_SUCCESS', response)
} catch(err) {
commit('SET_ERROR', error)
}
}
}
export const mutations = {
SET_SUCCESS(state, payload) {
state.success = payload
},
SET_ERROR(state, payload) {
state.error = payload
}
}
// auth.vue
export default {
methods: {
onLogin() {
try {
await this.$store.dispatch('auth/login', {
email: this.email,
password: this.password
})
if (this.$store.state.auth.success) this.$router.push('/home')
} catch (err) {
console.log(err)
}
}
}
}
// app.vue
export default {
created() {
this.$store.subscribe((mutation, state) => {
if (mutation.type.includes('ERROR')) {
// display error in global error output
console.log(mutation.payload)
}
})
}
}