feat(nuxt): make useFetch options reactive (#8374)

This commit is contained in:
Daniel Roe 2022-10-21 09:13:14 +01:00 committed by GitHub
parent f0c1dcb2d6
commit 69a6a86d7c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 4 deletions

View File

@ -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`).

View File

@ -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
}
@ -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 || [])
]