What is the exact difference between fetch and async data. The official documentation says the following:
asyncData
You may want
Let me re-iterate few points as a pretext to what i'm going to say
asyncData can set component level objects and access vuex storefetch cannot set component level objects but has access to vuex storeasyncData & fetch will be triggered in server side during initial loadasyncData and fetch will be triggered when the corresponding page routes are invoked1) if your design is
then use fetch
2) if your design is
then use asyncData
Can someone explain me the advantage of use these methods above the other?
i don't see any drawbacks in using asyncData or fetch
Choosing asyncData or fetch totally depends on your architecture
Several points mentioned in the answer no longer apply when using newer NuxtJS versions (>= 2.12). Official RFC announcement here.
A good explanation of the new behaviour and differences between asyncData and the new fetch can be found in this post in the NuxtJS official blog.
As for choosing between both, I believe the original answer still applies:
i don't see any drawbacks in using
asyncDataorfetchChoosing
asyncDataorfetchtotally depends on your architecture
TL;DR - use asyncData for stuff which must be loaded before rendering a page, use fetch for everything else.
Key differences:
asyncData is only available on page componentsfetch can be used on any component (including page components)asyncData blocks the page transition until it resolves. This means the data properties returned are guaranteed to be available on the component. But it also means users may have to wait longer before seeing content.fetch exposes a $fetchState.pending property and it's up to you how to handle thatasyncData the page is not renderedfetch exposes a $fetchState.error property and it's up to you how to handle thatI. fetch and asyncData are processed on the server-side.
II. can see the difference in the way to use them:
a) fetch: change store data
<script>
export default {
async fetch ({ store, params }) {
await store.dispatch('GET_STARS');
}
}
</script>
b) asyncData: change context (component data)
<script>
export default {
asyncData (context) {
return { project: 'nuxt' }
}
}
</script>
One point I'd like to make that I don't see mentioned above (at least, not clearly). asyncData automatically MERGES the data into your page's data() object. Fetch does not. With fetch, it's up to you to do with the data as you please.