gothinkster / vue-realworld-example-app

An exemplary real-world application built with Vue.js, Vuex, axios and different other technologies. This is a good example to discover Vue for beginners.
https://vue-vuex-realworld.netlify.com
MIT License
4.07k stars 1.3k forks source link

Transform Login call to async/await #58

Open igeligel opened 5 years ago

igeligel commented 5 years ago

Issue Summary:

In the auth.module.js here you have got some code like:

[LOGIN](context, credentials) {
  return new Promise(resolve => {
    ApiService.post("users/login", { user: credentials })
      .then(({ data }) => {
        context.commit(SET_AUTH, data.user);
        resolve(data);
      })
      .catch(({ response }) => {
        context.commit(SET_ERROR, response.data.errors);
      });
  });
}

Those promise calls could be simpliefied with async and await calls.

Resources:

Acceptance Criteria:

Main issue is here #5

ljones92 commented 5 years ago

I'll take a look at this

moozzyk commented 5 years ago

The problem with this one is that the original code never resolves or rejects the promise in case of errors. This is by itself incorrect. When converting this to async/await the promise will always be either resolved or rejected. This results in unwanted redirection to home in case of an error (because the error is not propagated, hence the promise gets resolved). This can be fixed by re-throwing the error from the catch block and swallowing it here like this:

    onSubmit(email, password) {
      this.$store
        .dispatch(LOGIN, { email, password })
        .then(() => this.$router.push({ name: "home" }))
        .catch(e => { /* the exception was already handled */});
    }

or by returning the data and checking inside the then for an error to know whether to redirect or not.