useAsyncData
Within your pages, components, and plugins you can use useAsyncData to get access to data that resolves asynchronously.
function useAsyncData( handler: (nuxtApp?: NuxtApp) => Promise<DataT>, options?: AsyncDataOptions<DataT>): AsyncData<DataT>function useAsyncData( key: string, handler: (nuxtApp?: NuxtApp) => Promise<DataT>, options?: AsyncDataOptions<DataT>): Promise<AsyncData<DataT>>type AsyncDataOptions<DataT> = { server?: boolean lazy?: boolean default?: () => DataT | Ref<DataT> | null transform?: (input: DataT) => DataT pick?: string[] watch?: WatchSource[] initialCache?: boolean immediate?: boolean}interface RefreshOptions { override?: boolean}type AsyncData<DataT, ErrorT> = { data: Ref<DataT | null> pending: Ref<boolean> execute: () => Promise<void> refresh: (opts?: RefreshOptions) => Promise<void> error: Ref<ErrorT | null>}
useAsyncData
will be generated for you.false
)lazy: true
optiontrue
)handler
function result after resolvinghandler
function resultfalse
, will skip payload cache for initial fetch. (defaults to true
)false
, will prevent the request from firing immediately. (defaults to true
)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.
handler
functionBy default, Nuxt waits until a refresh
is finished before it can be executed again.
server: false
), then the data will not be fetched until hydration completes. This means even if you await useAsyncData
on the client side, data
will remain null
within <script setup>
.const { data, pending, error, refresh } = await useAsyncData( 'mountains', () => $fetch('https://api.nuxtjs.dev/mountains'))