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/usefetch

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

useFetch status pending state

The pending status state indicates request is in progress.

useFetch status success state

The success status state indicates request completed successfully.

useFetch status error state

The error status state indicates request failed.

useFetch headers option

The headers option is type MaybeRefOrGetter<Record<string, string> | [key: string, value: string][] | Headers> with no default value. It specifies request headers.

useFetch baseURL option

The baseURL option is type MaybeRefOrGetter<string> with no default value. It specifies the base URL for the request.

useFetch composable signature

The useFetch composable has the signature: export function useFetch<ResT, ErrorT = NuxtError<unknown>, DataT = ResT>(url: string | Request | Ref<string | Request> | (() => string | Request), options?: UseFetchOptions<ResT, DataT>): AsyncData<DataT, ErrorT> & Promise<AsyncData<DataT, ErrorT>>. It takes a URL or Request object (can be string, Request, Vue ref, or function) and optional UseFetchOptions configuration object. It returns an AsyncData object combined with a Promise.

UseFetchOptions type definition

UseFetchOptions<ResT, DataT = ResT> configuration object has these properties: key (MaybeRefOrGetter<string>), method (MaybeRefOrGetter<string>), query (MaybeRefOrGetter<SearchParams>), params (MaybeRefOrGetter<SearchParams>), body (MaybeRefOrGetter<RequestInit['body'] | Record<string, any>>), headers (MaybeRefOrGetter<Record<string, string> | [key: string, value: string][] | Headers>), baseURL (MaybeRefOrGetter<string>), cache (false | 'default' | 'force-cache' | 'no-cache' | 'no-store' | 'only-if-cached' | 'reload'), server (boolean), lazy (boolean), immediate (boolean), getCachedData ((key: string, nuxtApp: NuxtApp, ctx: AsyncDataRequestContext) => DataT | undefined), deep (boolean), dedupe ('cancel' | 'defer'), timeout (number), enabled (MaybeRefOrGetter<boolean>), serialize (boolean), default (() => DataT | Ref<DataT>), transform ((input: ResT) => DataT | Promise<DataT>), pick (string[]), $fetch (typeof globalThis.$fetch), and watch (MultiWatchSources | false).

AsyncData return type

AsyncData<DataT, ErrorT> type includes: data (Ref<DataT | undefined>), pending (Ref<boolean>), refresh ((opts?: AsyncDataExecuteOptions) => Promise<void>), execute ((opts?: AsyncDataExecuteOptions) => Promise<void>), clear (() => void), error (Ref<ErrorT | undefined>), and status (Ref<AsyncDataRequestStatus>).

AsyncDataExecuteOptions type

AsyncDataExecuteOptions interface includes: dedupe ('cancel' | 'defer'), timeout (number), and signal (AbortSignal).

AsyncDataRequestStatus values

AsyncDataRequestStatus is a string type with values: 'idle', 'pending', 'success', or 'error'.

useFetch key option

The key option is type MaybeRefOrGetter<string> with default value 'auto-gen'. It provides a unique key for de-duplication. If not provided, it is generated from the URL, options, and call site location in the source code.

useFetch method option

The method option is type MaybeRefOrGetter<string> with default value 'GET'. It specifies the HTTP request method.

useFetch query and params options

The query option is type MaybeRefOrGetter<SearchParams> with no default value. The params option is also type MaybeRefOrGetter<SearchParams> with no default value. Query/search params append to the URL. params is an alias for query.

useFetch body option

The body option is type MaybeRefOrGetter<RequestInit['body'] | Record<string, any>> with no default value. It specifies the request body. Objects are automatically stringified.

useFetch cache option

The cache option is type false | string with no default value. Cache control: boolean disables cache, or use Fetch API values: 'default', 'no-store', 'force-cache', 'no-cache', 'only-if-cached', 'reload'.

useFetch server option

The server option is type boolean with default value true. It determines whether to fetch on the server.

useFetch lazy option

The lazy option is type boolean with default value false. If true, resolves after route loads (does not block navigation).

useFetch immediate option

The immediate option is type boolean with default value true. If false, prevents request from firing immediately.

useFetch default option

The default option is type () => DataT with no default value. It is a factory for default value of data before async resolves.

useFetch timeout option

The timeout option is type number with no default value (undefined means no timeout). It specifies a number in milliseconds to wait before timing out the request. Added in v4.2.

useFetch transform option

The transform option is type (input: DataT) => DataT | Promise<DataT> with no default value. It is a function to transform the result after resolving.

useFetch getCachedData option

The getCachedData option is type (key: string, nuxtApp: NuxtApp, ctx: AsyncDataRequestContext) => DataT | undefined with no default value. It is a function to return cached data. Added in v3.8. Default implementation: 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.

useFetch pick option

The pick option is type string[] with no default value. It specifies only pick specified keys from the result.

useFetch watch option

The watch option is type MultiWatchSources | false with no default value. It specifies array of reactive sources to watch and auto-refresh. false disables watching.

useFetch deep option

The deep option is type boolean with default value false. It determines whether to return data in a deep ref object. Defaults to false for improved performance (shallow ref object). Added in v3.8.

useFetch dedupe option

The dedupe option is type 'cancel' | 'defer' with default value 'cancel'. It avoids fetching same key more than once at a time. Added in v3.9.

useFetch enabled option

The enabled option is type MaybeRefOrGetter<boolean> with default value true. It is a barrier that gates whether the request 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. Added in v4.5.

useFetch serialize option

The serialize option is type boolean with default value true. It determines 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. Pair with lazy hydration to avoid hydration mismatches and unnecessary client fetches. Added in v4.6.

useFetch $fetch option

The $fetch option is type typeof globalThis.$fetch with no default value. It specifies a custom $fetch implementation. Added in v3.2.

useFetch data return value

The data return value is type Ref<DataT | undefined>. It is the result of the asynchronous fetch.

useFetch refresh and execute return values

Both refresh and execute return type (opts?: AsyncDataExecuteOptions) => Promise<void>. refresh is a function to manually refresh the data. By default, Nuxt waits until a refresh is finished before it can be executed again. execute is an alias for refresh.

useFetch error return value

The error return value is type Ref<ErrorT | undefined>. It is an error object if the data fetching failed.

useFetch status return value

The status return value is type Ref<'idle' | 'pending' | 'success' | 'error'>. Use it to distinguish idle, pending, success, and error states.

useFetch pending return value

The pending return value is type Ref<boolean>. It is true while a request is in flight. With experimental.pendingWhenIdle, it is also true when status is idle and no cached data is available.

useFetch clear return value

The clear return value is type () => void. It resets data to undefined (or the value of options.default() if provided), error to undefined, set status to idle, and cancels any pending requests.

useFetch status idle state

The idle status state indicates request has not started, such as when { immediate: false } or { server: false } on server render.

useFetch basic usage example

const { data, status, error, refresh, clear } = await useFetch('/api/modules', { pick: ['title'], }) This example shows how to fetch data from an endpoint, select only specific fields with pick, and handle the returned data, status, error, refresh and clear values.

useFetch reactive URL example

const route = useRoute() const id = computed(() => route.params.id) // When the route changes and id updates, the data will be automatically refetched const { data: post } = await useFetch(() => `/api/posts/${id.value}`) This example shows how to use a computed ref or function as the URL to enable dynamic data fetching that automatically updates when the URL changes.

useFetch query params example

const param1 = ref('value1') const { data, status, error, refresh } = await useFetch('/api/modules', { query: { param1, param2: 'value2' }, }) This example results in https://api.nuxt.com/modules?param1=value1&param2=value2. Query option extends from unjs/ofetch and uses unjs/ufo to create the URL. Objects are automatically stringified.

useFetch interceptors example

const { data, status, error, refresh, clear } = await useFetch('/api/auth/login', { onRequest ({ request, options }) { // Set the request headers // note that this relies on ofetch >= 1.4.0 - you may need to refresh your lockfile options.headers.set('Authorization', '...') }, onRequestError ({ request, options, error }) { // Handle the request errors }, onResponse ({ request, response, options }) { // Process the response data localStorage.setItem('token', response._data.token) }, onResponseError ({ request, response, options }) { // Handle the response errors }, }) This example shows how to use interceptors with useFetch to modify requests, handle errors, and process responses.

useFetch shared state with key example

// ComponentA.vue const { data } = await useFetch('/api/random', { key: 'random' }) // ComponentB.vue const { data } = await useFetch('/api/random', { key: 'random' }) With the same explicit key provided to each call, the data, error and status refs are shared across different components, and only one request is made.

useFetch reactive watch example

const searchQuery = ref('initial') const { data } = await useFetch('/api/search', { query: { q: searchQuery }, }) // triggers a refetch: /api/search?q=new%20search searchQuery.value = 'new search' When a reactive fetch option like query is updated, it will trigger a refetch using the updated resolved reactive value.

useFetch disable watch example

const searchQuery = ref('initial') const { data } = await useFetch('/api/search', { query: { q: searchQuery }, watch: false, }) // does not trigger a refetch searchQuery.value = 'new search' Using watch: false opts out of automatic refetch behavior when reactive options change.

useFetch reserved function name warning

useFetch is a reserved function name transformed by the compiler, so you should not name your own function useFetch. To create a custom variant with pre-defined options, use createUseFetch instead.

useFetch import conflict with @vueuse/core

If data destructured from useFetch returns a string and not a JSON parsed object, make sure your component doesn't include an import statement like import { useFetch } from '@vueuse/core'. This causes a naming conflict.

useFetch refs and functions behavior

data, status, and error are Vue refs and should be accessed with .value when used within <script setup>. refresh/execute and clear are plain functions.

useFetch await behavior

You do not need to await useFetch. On the server, Nuxt waits for the promise to resolve before rendering in either case, so the returned HTML always contains the data. The await affects what happens after the call: with it, execution pauses until data is populated and client-side navigation is blocked until the data is ready; without it, execution continues immediately, data starts as its default value until the request resolves, and on client-side navigation you handle the loading and error states yourself. This has a similar effect to the lazy option, though lazy is the explicit way to opt into non-blocking navigation.

useFetch automatic key generation

The auto-generated key is unique to each call site, so calling useFetch with the same URL and options in different components will not share state and each call performs its own request. Multiple instances of the same component do share state, since they use the same call site.

useFetch server data on client hydration

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 useFetch on client-side, data will remain undefined within <script setup>.

useFetch all options support reactivity

All fetch 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 (unless watch is set to false).

useFetch purpose and wrapper

useFetch is a composable that provides a convenient wrapper around useAsyncData and $fetch. It automatically generates a key for the request, provides type hints for request url based on server routes, and infers API response type.

useFetch usage context

useFetch is a composable meant to be called directly in a setup function, plugin, or route middleware. It 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.

AsyncDataRequestContext type

AsyncDataRequestContext type includes: cause (string indicating the reason for this data request: 'initial', 'refresh:manual', 'refresh:hook', or 'watch').

Give your agent this brain