NuxtJS - Use asyncData method in layout or component

Viewed 15203

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,
      };
    }
  })
2 Answers

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')
  }
}

The new fetch on Nuxt >= 2.12 now supports fetching on the layout and component level.

Right now it's slightly broken for me on the layout level for my statically generated site so I use fetchOnServer: false. By the time future people read this it'll hopefully be fixed, so feel free to edit this out.

Here's some useful reading material :)

Docs

General guide

Guide for static sites

Related