Home » vue » then() in promise is always executed which is in Vue component even if i get an error from catch() which is in Vuex action

then() in promise is always executed which is in Vue component even if i get an error from catch() which is in Vuex action

Posted by: admin November 26, 2021 Leave a comment

Questions:

I am setting up authentication using apollo-vue graphql. To redirect user to homepage when he/she successfully logs in. I’ve returned promise from Vuex action and used then() in Vue component where i push my node in route for redirection but then() in Vue component is always executed even if i get error from catch() which is in vuex actions and user is always redirected to homepage

I’ve tried adding catch after then() in Vue component and it works but i want to capture my error in vuex not in vue component

Action in Vuex

login(){
 return apollo
  .mutate({
    mutation: CREATE_SHOP_USER,
    variables: signUpData
    })
   .then((res) => console.log(res))
   .catch((err) => console.log(err))
}

Method in Vue Component

 userAuthenticate() {
      const userSignupData = {
        email: this.email,
        password: this.password
      };

      this.$store
        .dispatch("authenticateApp", userSignupData)
        .then(() => {
          this.$router.push("/");
        })        

I expect “then” in Vue component should never be executed if catch has been already executed which is in Vuex action.

Answers:

You can log the error inside the vuex action, but you’ll need to throw it again in order to still have the promise reject:

return apollo.mutate({
  mutation: CREATE_SHOP_USER,
  variables: signUpData
})
  .then((res) => console.log(res))
  .catch((err) => {
    console.log(err)
    throw err
  })

This will prevent the then inside your component from being called. Of course, because we now have a rejected promise, we should still handle the rejection:

this.$store
  .dispatch("authenticateApp", userSignupData)
  .then(() => {
    this.$router.push("/");
  })
  .catch(() => {
    // Handle rejection here
  })