useAsyncData

Within your pages, components, and plugins you can use useAsyncData to get access to data that resolves asynchronously.

Type

Signature

  1. function useAsyncData(
  2. key: string,
  3. handler: (nuxtApp?: NuxtApp) => Promise<DataT>,
  4. options?: AsyncDataOptions
  5. ): Promise<DataT>
  6. type AsyncDataOptions = {
  7. server?: boolean
  8. lazy?: boolean
  9. default?: () => DataT | Ref<DataT>
  10. transform?: (input: DataT) => DataT
  11. pick?: string[]
  12. watch?: WatchSource[]
  13. initialCache?: boolean
  14. }
  15. type DataT = {
  16. data: Ref<DataT>
  17. pending: Ref<boolean>
  18. refresh: () => Promise<void>
  19. error: Ref<any>
  20. }

Params

  • key: a unique key to ensure that data fetching can be properly de-duplicated across requests
  • handler: an asynchronous function that returns a value
  • options:
    • lazy: whether to resolve the async function after loading the route, instead of blocking navigation (defaults to false)
    • default: a factory function to set the default value of the data, before the async function resolves - particularly useful with the lazy: true option
    • server: whether to fetch the data on the server (defaults to true)
    • transform: a function that can be used to alter handler function result after resolving
    • pick: only pick specified keys in this array from the handler function result
    • watch: watch reactive sources to auto-refresh
    • initialCache: When set to false, will skip payload cache for initial fetch. (defaults to true)
    • default: A function that returns the default value (before the handler function returns its value).

Under the hood, lazy: false uses <Suspense> to block the loading of the route before the data has been fetched. Consider using lazy: true and implementing a loading state instead for a snappier user experience.

Return values

  • data: the result of the asynchronous function that is passed in
  • pending: a boolean indicating whether the data is still being fetched
  • refresh: a function that can be used to refresh the data returned by the handler function
  • error: an error object if the data fetching failed

By default, Nuxt waits until a refresh is finished before it can be executed again. Passing true as parameter skips that wait.

Example

  1. const { data, pending, error, refresh } = useAsyncData(
  2. 'mountains',
  3. () => $fetch('https://api.nuxtjs.dev/mountains),
  4. {
  5. pick: ['title']
  6. }
  7. )

👉

Read more in Guide > Features > Data Fetching.