Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

feat(nuxt): make useFetch options reactive #8374

Merged
merged 1 commit into from Oct 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/content/3.api/1.composables/use-fetch.md
Expand Up @@ -47,6 +47,11 @@ type AsyncData<DataT> = {
* `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`).
Expand Down
15 changes: 11 additions & 4 deletions 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<ReqT extends NitroFetchRequest> = TypedInternalResponse<ReqT, unknown>

type ComputedOptions<T extends Record<string, any>> = {
[K in keyof T]: T[K] extends Function ? T[K] : T[K] extends Record<string, any> ? ComputedOptions<T[K]> | Ref<T[K]> | T[K] : Ref<T[K]> | T[K]
}

type ComputedFetchOptions = ComputedOptions<FetchOptions>

export interface UseFetchOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> extends AsyncDataOptions<DataT, Transform, PickKeys>, FetchOptions {
> extends AsyncDataOptions<DataT, Transform, PickKeys>, ComputedFetchOptions {
key?: string
}

Expand Down Expand Up @@ -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,
Expand All @@ -81,6 +87,7 @@ export function useFetch<
initialCache,
immediate,
watch: [
_fetchOptions,
_request,
...(watch || [])
]
Expand Down