1

I have a no module store and I have an action loginUser, which logins the user by saving the authorization header in the state:

loginUser(context, user) {
      userService.login(user)
          .then(response => context.commit('SET_AUTHORIZATION', response.data))
          .catch(error => { throw error.response.data })
    }

The problem is that I need the error in the login component and I can't store it in the state, since I made the store to be persistent as long as the session is active. My submit function in the login component looks like this:

  async onSubmit() {
        let user = {
          username: this.username,
          password: this.password,
        }
        await this.$store.dispatch('loginUser', user)
              .catch(error => {
                  if(error.response.status === 401) this.loginError = error.message
                  else console.error(error)
        })
        await this.$router.push('/').then(() => location.reload())
      }
    },

This just throws an Uncaught (in promise).

1 Answer 1

3

You can return a Promise from your loginUser action like:

loginUser(context, user) {
  return new Promise((resolve, reject) => {
    userService.login(user)
      .then((response) => {
        context.commit('SET_AUTHORIZATION', response.data)
        resolve(response)
      })
      .catch((error) => {
        reject(error.response.data)
      })
  })
}

and then you can update your async onSubmit() method and catch that error using try..catch like:

async onSubmit() {

  try {
    let user = {
      username: this.username,
      password: this.password,
    }
    await this.$store.dispatch('loginUser', user);
    await this.$router.push('/');
    location.reload();
  } catch (error) {
    if (error.response && error.response.status === 401) 
      this.loginError = error.message
    else 
      console.error(error)
  }

},
Sign up to request clarification or add additional context in comments.

1 Comment

I'm not really familiar with promises, but I thought that both then and catch return a promise. So that the thrown error would propagate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.