Skip to content

Commit

Permalink
feat(useFetch): add initialData option (vitest-dev#714)
Browse files Browse the repository at this point in the history
Co-authored-by: junjianlin <junjianlin@xiaoman.cn>
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
3 people committed Sep 8, 2021
1 parent 9e006e3 commit df3ad58
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions packages/core/useFetch/index.ts
Expand Up @@ -137,6 +137,13 @@ export interface UseFetchOptions {
*/
refetch?: MaybeRef<boolean>

/**
* Initial data before the request finished
*
* @default null
*/
initialData?: any

/**
* Will run immediately before the fetch request is dispatched
*/
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -252,6 +259,7 @@ export function useFetch<T>(url: MaybeRef<string>, ...args: any[]): UseFetchRetu

const {
fetch = defaultWindow?.fetch,
initialData,
} = options

// Event Hooks
Expand All @@ -265,7 +273,7 @@ export function useFetch<T>(url: MaybeRef<string>, ...args: any[]): UseFetchRetu
const statusCode = ref<number | null>(null)
const response = shallowRef<Response | null>(null)
const error = ref<any>(null)
const data = shallowRef<T | null>(null)
const data = shallowRef<T | null>(initialData)

const canAbort = computed(() => supportsAbort && isFetching.value)

Expand Down Expand Up @@ -341,9 +349,7 @@ export function useFetch<T>(url: MaybeRef<string>, ...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)
Expand Down

0 comments on commit df3ad58

Please sign in to comment.