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

2 Answers 2

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')
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

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.
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.
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.
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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.