NuxtJS - Use asyncData method in layout or component

11,888

Solution 1

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

Solution 2

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

Share:
11,888

Related videos on Youtube

pirmax
Author by

pirmax

Updated on June 04, 2022

Comments

  • pirmax
    pirmax almost 2 years

    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,
          };
        }
      })
    
  • King Holly
    King Holly over 3 years
    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.
  • Mark Sonn
    Mark Sonn over 3 years
    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.
  • King Holly
    King Holly over 3 years
    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.
  • Mark Sonn
    Mark Sonn over 3 years
    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 :)