Search code examples
typescriptvue.jsvue-componentnuxt.jsasyncdata

NuxtJS - Use asyncData method in layout or component


How I can use asyncData in layout or component (forbidden apparently) ?

Because my sidebar component is used in default layout, and I need to use asyncData to display data from backend. And if I use Vuex to fetch data... I don't know how I can fetch this with global on every page.

My layout component annotation:

  @Component({
    components: {
      LeftDrawer
    },
    async asyncData({ app }) {
      const latestPosts = await app.$axios.get(`/posts/latest`);

      return {
        latestPosts: latestPosts.data,
      };
    }
  })

Solution

  • fetch and asyncData works only for pages, as it stated in documentation. If you need something to get data on each page, use nuxtServerInit

    actions: {
      async nuxtServerInit({ dispatch }) {
        await dispatch('core/load')
      }
    }