diff --git a/docs/content/3.api/1.composables/use-fetch.md b/docs/content/3.api/1.composables/use-fetch.md index 6e2148c0eb8..8f4e4a193fc 100644 --- a/docs/content/3.api/1.composables/use-fetch.md +++ b/docs/content/3.api/1.composables/use-fetch.md @@ -47,6 +47,11 @@ type AsyncData = { * `body`: Request body - automatically stringified (if an object is passed). * `headers`: Request headers. * `baseURL`: Base URL for the request. + +::alert{type=info} +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. +:: + * **Options (from `useAsyncData`)**: * `key`: a unique key to ensure that data fetching can be properly de-duplicated across requests, if not provided, it will be generated based on the static code location where `useAyncData` is used. * `server`: Whether to fetch the data on the server (defaults to `true`). diff --git a/packages/nuxt/src/app/composables/fetch.ts b/packages/nuxt/src/app/composables/fetch.ts index 229617c9d01..bf23534ca7c 100644 --- a/packages/nuxt/src/app/composables/fetch.ts +++ b/packages/nuxt/src/app/composables/fetch.ts @@ -1,16 +1,22 @@ import type { FetchError, FetchOptions } from 'ohmyfetch' import type { TypedInternalResponse, NitroFetchRequest } from 'nitropack' -import { computed, unref, Ref } from 'vue' +import { computed, unref, Ref, reactive } from 'vue' import type { AsyncDataOptions, _Transform, KeyOfRes, AsyncData, PickFrom } from './asyncData' import { useAsyncData } from './asyncData' export type FetchResult = TypedInternalResponse +type ComputedOptions> = { + [K in keyof T]: T[K] extends Function ? T[K] : T[K] extends Record ? ComputedOptions | Ref | T[K] : Ref | T[K] +} + +type ComputedFetchOptions = ComputedOptions + export interface UseFetchOptions< DataT, Transform extends _Transform = _Transform, PickKeys extends KeyOfRes = KeyOfRes -> extends AsyncDataOptions, FetchOptions { +> extends AsyncDataOptions, ComputedFetchOptions { key?: string } @@ -67,10 +73,10 @@ export function useFetch< ...fetchOptions } = opts - const _fetchOptions = { + const _fetchOptions = reactive({ ...fetchOptions, cache: typeof opts.cache === 'boolean' ? undefined : opts.cache - } + }) const _asyncDataOptions: AsyncDataOptions<_ResT, Transform, PickKeys> = { server, @@ -81,6 +87,7 @@ export function useFetch< initialCache, immediate, watch: [ + _fetchOptions, _request, ...(watch || []) ]