From df3ad582fe588915a5aa964da10ef1d4e8e6a438 Mon Sep 17 00:00:00 2001 From: Jay214 Date: Thu, 9 Sep 2021 01:16:35 +0800 Subject: [PATCH] feat(useFetch): add `initialData` option (#714) Co-authored-by: junjianlin Co-authored-by: Anthony Fu --- packages/core/useFetch/index.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/packages/core/useFetch/index.ts b/packages/core/useFetch/index.ts index db61e93eb251..40b1b9468fd4 100644 --- a/packages/core/useFetch/index.ts +++ b/packages/core/useFetch/index.ts @@ -137,6 +137,13 @@ export interface UseFetchOptions { */ refetch?: MaybeRef + /** + * Initial data before the request finished + * + * @default null + */ + initialData?: any + /** * Will run immediately before the fetch request is dispatched */ @@ -173,7 +180,7 @@ export interface CreateFetchOptions { * to include the new options */ function isFetchOptions(obj: object): obj is UseFetchOptions { - return containsProp(obj, 'immediate', 'refetch', 'beforeFetch', 'afterFetch') + return containsProp(obj, 'immediate', 'refetch', 'initialData', 'beforeFetch', 'afterFetch') } function headersToObject(headers: HeadersInit | undefined) { @@ -252,6 +259,7 @@ export function useFetch(url: MaybeRef, ...args: any[]): UseFetchRetu const { fetch = defaultWindow?.fetch, + initialData, } = options // Event Hooks @@ -265,7 +273,7 @@ export function useFetch(url: MaybeRef, ...args: any[]): UseFetchRetu const statusCode = ref(null) const response = shallowRef(null) const error = ref(null) - const data = shallowRef(null) + const data = shallowRef(initialData) const canAbort = computed(() => supportsAbort && isFetching.value) @@ -341,9 +349,7 @@ export function useFetch(url: MaybeRef, ...args: any[]): UseFetchRetu if (options.afterFetch) ({ data: responseData } = await options.afterFetch({ data: responseData, response: fetchResponse })) - data.value = responseData as any - // see: https://www.tjvantoll.com/2015/09/13/fetch-and-errors/ if (!fetchResponse.ok) throw new Error(fetchResponse.statusText)