4

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,
      };
    }
  })
pirmax
  • 2,054
  • 8
  • 36
  • 69

2 Answers2

9

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')
  }
}
Aldarund
  • 17,312
  • 5
  • 73
  • 104
6

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

Mark Sonn
  • 848
  • 8
  • 22
  • I am also noticing issues with `async fetch()` when combined with `target: "static"` in my Nuxt config. `fetchOnServer: false` fixes my issue for some components, but when applied to others, it breaks my build...Still troubleshooting. – King Holly Oct 29 '20 at 06:05
  • Make another Stack Overflow question and tag me, I'll see if I can see something obvious. If not, you might need to make a Github issue. – Mark Sonn Nov 02 '20 at 01:51
  • Our current solution which my coworker found is to do `created() { this.$fetch(); }` I asked him about it and his theory is that in the server `mounted()` won't run until `created()` is done. Since we call the fetch API in the created lifecycle method, the data will be available when the mounted lifecycle method runs. The QA passed, so I am assuming this method works for our use case of fetching yaml translation files on build. – King Holly Nov 03 '20 at 01:12
  • 1
    Glad you got it working, still worth making a Github issue so they they can either fix this or add it to the docs. Good luck with the rest of your project :) – Mark Sonn Nov 06 '20 at 07:06