Home > Software engineering >  How can use await/async in vue mounted
How can use await/async in vue mounted

Time:04-27

I am trying to use mapGetters value in my other computed property. It showing null because the preferences method not executed completed. I want to wait until the store set the getter and setter. I am tried async/await but it's not working

mounted() {
  this.preferences();
  this.selectedColumnsHeader;
},

methods: {
  async preferences() {
    await this.$store.dispatch('fetchPreferences');
  }
}

store

fetchPreferences({ commit }) {
  return http
    .get('/help_ticket_preferences.json')
    .then((res) => {
      commit('setDefaultSelectedColumns', res.data.defaultSelectedCols);
      commit('setDefaultUnSelectedColumns', res.data.defaultUnselectedCols);
      commit('setHelpTicketPreferences', res.data.helpTicketPreference.preference);
    })
    .catch((error) => {
      commit('setErrorMessage', `Sorry, there was an error fetching help ticket preferences ${error.message}.`);
    });
},

CodePudding user response:

Firstly, you need to await for this.preferences() in mounted

async mounted() {
  await this.preferences();
  this.selectedColumnsHeader;
},

secondly, you need to return a Promise in fetchPreferences

fetchPreferences({ commit }) {
  return http
    .get('/help_ticket_preferences.json')
    ..... etc

Hoe that helps

  • Related