Distinguishing between AsyncData and Fetch in Nuxtjs

Tram Ho

Preamble

When working with nuxtJS you will come across two concepts: fetch and asyncData . These two methods are similar in usage: they allow asynchronous event handling and return results and have one input parameter called context (in the context there are variables store, params, isDev, …). What is the difference between which of the two methods is the intended use? Both fetch and asyncData are called only once (the first time when the request is directed to the server) and called each time by the client when it is moved to the corresponding page.

Fetch

The purpose is to get data from the api and re-update it in the app store, then get data from the store to use, this function does not return data.

Some notes are as follows:

  1. When calling APIs or washing actions in fetch, async / await must be handled asynchronously.
  2. Fetch can be used in both page components and other components.
  3. Use this and can receive the given context .
  4. Fetch calls on the server-side once and every time on the client-side when the route changes.

AsyncData

Also retrieves data from api, but does not update to the store, but this function returns as object, the value of this object will be used in the component that is always not updated in the store and this value will be merged with the ban value. the head you declare in the data attribute. asyncData is usually called if you just want to get data from the server and display the component too, not store it in the store.

Some notes are as follows:

  1. When calling the API or washing actions in asyncData, async / await must be handled asynchronously.
  2. AsyncData can only be used in page components.
  3. AsyncData is called before fetch and called once on the server-side and each time before the router is changed on the client-side.
  4. AsyncData takes the context as the first argument and has no access by this of the component instance

So through this article I also learned the similarity as well as the difference between the two methods fetch and asyncData. When to use which method. Hope to be of some help to you, thank you for reading my articles!

References:

  1. https://medium.com/@nestsera/nuxtjs-lifecycle-8a822af2c5a8
  2. https://nuxtjs.org/blog/understanding-how-fetch-works-in-nuxt-2-12/
  3. https://morioh.com/p/289c1f5b44ee
Share the news now

Source : Viblo