Home » vue » Async / Await Vuex

Async / Await Vuex

Posted by: admin November 26, 2021 Leave a comment

Questions:

I want to call an action in created hook, wait until is done and in same hook to display the result. Is that possible?

I tried to put async / await in actions but doesn’t help.
This is the action property with the async function in the store:

 actions: {
    async FETCH_USER({commit}) {
      await firebase.firestore().collection('test').get().then(res => {
        commit('FETCH_USER', res.docs[0].data())
      })
    }
  }
   created() {
     this.FETCH_USER()
     console.log(this.GET_USER)
   },
   methods: {
     ...mapActions([
       'FETCH_USER'
     ]),
     login() {
       if(this.$refs.form.validate()) {
         console.log('welcome')
       }
     }
   },
   computed: {
     ...mapGetters([
       'GET_USER'
     ])
   }
export default new Vuex.Store({
  state: {
    user: null
  },
  getters: {
    GET_USER: state => state.user
  },
  mutations: {
    FETCH_USER(state, user) {
      state.user = user
    }
  },
  actions: {
    FETCH_USER({commit}) {
      firebase.firestore().collection('test').get().then(res => {
        commit('FETCH_USER', res.docs[0].data())
      })
    }
  }
})
Answers:

async/await version

async FETCH_USER({ commit }) {
  const res = await firebase.firestore().collection('test').get()
  const user = res.docs[0].data()
  commit('FETCH_USER', user)
  return user
}
async created() {
  // The action returns the user out of convenience
  const user = await this.FETCH_USER()
  console.log(user)

  // -- or --

  // Access the user through the getter
  await this.FETCH_USER()
  console.log(this.GET_USER)
}

You need to await the action call because it is an async function.

Promise version

FETCH_USER({ commit }) {
  return firebase.firestore().collection('test').get().then(res => {
    const user = res.docs[0].data()
    commit('FETCH_USER', user)
    return user
  })
}
created() {
  this.FETCH_USER().then(user => {
    console.log(user)
  })

  // -- or --

  this.FETCH_USER().then(() => {
    console.log(this.GET_USER)
  })
}