[Vuejs]-How to make the nuxt child component wait until asyncData call get finish

0👍

In my case, I used asyncData in my parent nuxt component, which fetches the data via store dispatch action, then set it to some store state key, via mutation.

Then I used validate method in my child component. Since Nuxt validate can return promises, I checked the vuex store first for fetched data. If there is none, I refetch it and return the promise instead.

In Parent component.vue

export default {
  async asyncData({ params, store }) {
       // Api operation which may take sometime
       const {data} = await store.dispatch('fetch-my-data')
       store.commit('setData', data) //This should be within above dispatch, but here for relevance 
  }
}

Here I am only fetching and saving to vuex store.

Child component.vue

export default {
   async validate({ params, store }) {
      let somedata = store.state.data //This is what you've set via parent's component mutation
      return !!somedata || store.dispatch('fetch-my-data')
   }
}

Here I am returning either the vuex store data (if exists), else refetch it.

Leave a comment