Vuex: How to wait for action to finish?

Your action is returning a promise so you can console after the promise has been resolved in then() block.

login() {
  let user = {
    email: this.email,
    password: this.password
  };

  this.$store.dispatch('auth/login', user).then(() => {
   console.log(this.$store.getters['auth/getAuthError'])
   // this.$router.push('/') // Also, its better to invoke router's method from a component than in a store file, anyway reference of a component may not be defined in the store file till you explicity pass it
  })
},

OR, you can make login an async function & wait for the action till promise returned by action has been resolved

async login() {
  let user = {
    email: this.email,
    password: this.password
  };

  await this.$store.dispatch('auth/login', user)
  console.log(this.$store.getters['auth/getAuthError'])
},

You can use async-await instead of Promise.then. But my suggestion is not to use Axios inside the store. Call Axios inside the login method and then call the store. Something like this:

methods: {
    async login() {
        try {
            const result = await axios.post('http://localhost:8000/api/user/login', this.user);
            this.$store.dispatch('auth/login', result);
        } catch (err) {
            console.log(err);
        }
    }
}

And then you just need to set the Object in your store.

Tags:

Vue.Js

Vuex