new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Nuxt · API · all subjects

composables/use-async-data

27 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

useAsyncData server-side rendering behavior

On the server, Nuxt waits for the promise to resolve before rendering in either case, so the returned HTML always contains the data.

useAsyncData status values

Status values are: 'idle' (function has not been called yet, e.g. { immediate: false } or { server: false } on server render), 'pending' (function has been called and promise is pending), 'success' (function returned a value), 'error' (function threw an error).

useAsyncData composable signature - overloads

useAsyncData has two overloads. The first takes a handler function and optional AsyncDataOptions. The second takes a key (MaybeRefOrGetter<string>), handler function, and optional AsyncDataOptions. Both return AsyncData<DataT, DataE> & Promise<AsyncData<DataT, DataE>>. The AsyncDataHandler type is (nuxtApp: NuxtApp, options: { signal: AbortSignal }) => Promise<ResT>.

useAsyncData options table

AsyncDataOptions<ResT, DataT = ResT> configuration options: | Option | Type | Default | Description | |--------|------|---------|-------------| | server | boolean | true | Whether to call the function on the server. | | lazy | boolean | false | If true, resolves after route loads (does not block navigation). | | immediate | boolean | true | If false, prevents function from being called immediately. | | default | () => DataT | - | Factory for default value of data before async resolves. | | deep | boolean | false | Return data in a deep ref object. Defaults to false for improved performance (shallow ref object). | | dedupe | 'cancel' \| 'defer' | 'cancel' | Policy when triggering an execution more than once at a time. | | enabled | boolean | true | Barrier that gates whether the handler may run. While false, every execution is blocked (initial fetch, execute/refresh, and watch triggers), and switching true → false cancels any in-flight request without clearing data. Re-enabling does not refetch on its own. | | serialize | boolean | true | Whether to store resolved data in the Nuxt payload (__NUXT_DATA__). When false, server-fetched data is kept out of the payload and the client will refetch after hydration if a component renders it. | | timeout | number | undefined | A number in milliseconds to wait before timing out the call. Defaults to undefined, which means no timeout. | | transform | (input: ResT) => DataT \| Promise<DataT> | - | Function to transform the result after resolving. | | pick | string[] | - | Only pick specified keys from the result. | | watch | MultiWatchSources | - | Array of reactive sources to watch and auto-refresh. | | getCachedData | (key: string, nuxtApp: NuxtApp, ctx: AsyncDataRequestContext) => DataT \| undefined | - | Function to return cached data. | AsyncDataRequestContext is an object with cause: 'initial' | 'refresh:manual' | 'refresh:hook' | 'watch'.

useAsyncData AsyncDataExecuteOptions

AsyncDataExecuteOptions interface for refresh/execute: { dedupe?: 'cancel' | 'defer', timeout?: number, signal?: AbortSignal }.

useAsyncData basic usage example

Example showing useAsyncData with key, handler, and destructured return values: const { data, status, pending, error, refresh, clear } = await useAsyncData('mountains', (_nuxtApp, { signal }) => $fetch('https://api.nuxtjs.dev/mountains', { signal }))

useAsyncData watch parameters example

Example showing automatic rerunning with watch option: const page = ref(1); const { data: posts } = await useAsyncData('posts', (_nuxtApp, { signal }) => $fetch('https://fakeApi.com/posts', { params: { page: page.value }, signal }), { watch: [page] }). When page changes, the fetcher function automatically reruns.

useAsyncData reactive keys example

Example using computed ref as key for dynamic data fetching: const route = useRoute(); const userId = computed(() => `user-${route.params.id}`); const { data: user } = useAsyncData(userId, () => fetchUserById(route.params.id)). When route changes and userId updates, data is automatically refetched.

useAsyncData abortable handler with signal

Example making handler abortable using AbortSignal: const { data, error } = await useAsyncData('users', (_nuxtApp, { signal }) => $fetch('/api/users', { signal })). The signal can be passed to $fetch to support cancellation. Calling refresh() will cancel the request if dedupe: 'cancel' is set.

useAsyncData manual abort control example

Example of manually controlling abort with AbortController: const { refresh } = await useAsyncData('users', (_nuxtApp, { signal }) => $fetch('/api/users', { signal })); let abortController: AbortController | undefined; function handleUserAction() { abortController = new AbortController(); refresh({ signal: abortController.signal }); } function handleCancel() { abortController?.abort(); }

useAsyncData custom abort logic example

Example implementing custom abort logic without native abort signal support: const { data, error } = await useAsyncData('users', (_nuxtApp, { signal }) => { return new Promise((resolve, reject) => { signal?.addEventListener('abort', () => { reject(new Error('Request aborted')) }); return Promise.resolve(callback.call(this, yourHandler)).then(resolve, reject); }); })

useAsyncData handler signal abort conditions

The handler signal is aborted when: a new request is made with dedupe: 'cancel', the clear function is called, or the options.timeout duration is exceeded.

useAsyncData shared state option consistency

When multiple useAsyncData calls use the same key, they share the same data, error, status, and pending refs. Options that MUST be consistent across calls with the same key: handler function, deep option, transform function, pick array, getCachedData function, default value. Options that CAN differ: server, lazy, immediate, dedupe, watch, enabled, serialize.

useAsyncData handler must be side-effect free

The handler function should be side-effect free to ensure predictable behavior during SSR and CSR hydration. If side effects are needed, use the callOnce utility.

useAsyncData default getCachedData implementation

The default getCachedData implementation is: const getDefaultCachedData = (key, nuxtApp, ctx) => nuxtApp.isHydrating ? nuxtApp.payload.data[key] : nuxtApp.static.data[key]. This only caches data when experimental.payloadExtraction in nuxt.config is enabled.

useAsyncData await behavior and lazy option

Awaiting useAsyncData affects execution flow. With await, execution pauses until data is populated and client-side navigation is blocked until data is ready. Without await, execution continues immediately with data starting as default value, and on client-side navigation you handle loading and error states using returned status and error refs. This is similar to the lazy option effect, though lazy is the explicit way to opt in to non-blocking navigation.

useAsyncData ref access patterns

data, status, pending, and error are Vue refs and require accessing their values with .value in <script setup>. refresh/execute and clear are plain functions and do not need .value.

useAsyncData prevents SSR re-fetching

useAsyncData returns reactive composables and handles adding responses to the Nuxt payload so they can be passed from server to client without re-fetching the data on client side when the page hydrates.

useAsyncData pending with experimental.pendingWhenIdle

The pending ref is true while a request is in flight. With experimental.pendingWhenIdle feature enabled, pending is also true when status is idle and no cached data is available.

useAsyncData clear function behavior

The clear function resets data to undefined (or the value of options.default() if provided), error to undefined, sets status to idle, and cancels any pending calls.

useAsyncData key parameter details

The key parameter is a unique key to ensure that data fetching can be properly de-duplicated across requests. If a key is not provided, a key that is unique to the file name and line number of the instance of useAsyncData is generated automatically.

useAsyncData handler return value requirement

The handler function must return a truthy value (for example, it should not be undefined or null) or the request may be duplicated on the client side.

useAsyncData compiler transformation warning

useAsyncData is a reserved function name transformed by the compiler, so you should not name your own function useAsyncData.

useAsyncData with server: false client-side fetching behavior

If you have not fetched data on the server (for example, with 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 undefined within <script setup>.

useAsyncData all options can be reactive

All options can be given a computed or ref value. These will be watched and new requests made automatically with any new values if they are updated.

useAsyncData lazy option blocks route loading

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.

useAsyncData promise destructuring

Functions from the Promise (then, catch, and finally) can safely be destructured, if you did not await the return value.

Give your agent this brain