NuxtJS - Use asyncData method in layout or component
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 :)
Related videos on Youtube
pirmax
Updated on June 04, 2022Comments
-
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 over 3 yearsI am also noticing issues with
async fetch()
when combined withtarget: "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 over 3 yearsMake 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 over 3 yearsOur current solution which my coworker found is to do
created() { this.$fetch(); }
I asked him about it and his theory is that in the servermounted()
won't run untilcreated()
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 over 3 yearsGlad 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 :)