MCPcopy
hub / github.com/vueuse/vueuse / useFetch

Function useFetch

packages/core/useFetch/index.ts:337–646  ·  view source on GitHub ↗
(url: MaybeRefOrGetter<string>, ...args: any[])

Source from the content-addressed store, hash-verified

335export function useFetch<T>(url: MaybeRefOrGetter<string>, options: RequestInit, useFetchOptions?: UseFetchOptions): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
336
337export function useFetch<T>(url: MaybeRefOrGetter<string>, ...args: any[]): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>> {
338 const supportsAbort = typeof AbortController === 'function'
339
340 let fetchOptions: RequestInit = {}
341 let options: UseFetchOptions = {
342 immediate: true,
343 refetch: false,
344 timeout: 0,
345 updateDataOnError: false,
346 }
347
348 interface InternalConfig {
349 method: HttpMethod
350 type: DataType
351 payload: unknown
352 payloadType?: string
353 }
354
355 const config: InternalConfig = {
356 method: 'GET',
357 type: 'text' as DataType,
358 payload: undefined as unknown,
359 }
360
361 if (args.length > 0) {
362 if (isFetchOptions(args[0]))
363 options = { ...options, ...args[0] }
364 else
365 fetchOptions = args[0]
366 }
367
368 if (args.length > 1) {
369 if (isFetchOptions(args[1]))
370 options = { ...options, ...args[1] }
371 }
372
373 const {
374 fetch = defaultWindow?.fetch ?? globalThis?.fetch,
375 initialData,
376 timeout,
377 } = options
378
379 // Event Hooks
380 const responseEvent = createEventHook<Response>()
381 const errorEvent = createEventHook<any>()
382 const finallyEvent = createEventHook<any>()
383
384 const isFinished = shallowRef(false)
385 const isFetching = shallowRef(false)
386 const aborted = shallowRef(false)
387 const statusCode = shallowRef<number | null>(null)
388 const response = shallowRef<Response | null>(null)
389 const error = shallowRef<any>(null)
390 const data = shallowRef<T | null>(initialData || null)
391
392 const canAbort = computed(() => supportsAbort && isFetching.value)
393
394 let controller: AbortController | undefined

Callers 2

index.test.tsFile · 0.90
useFactoryFetchFunction · 0.70

Calls 7

createEventHookFunction · 0.90
useTimeoutFnFunction · 0.90
toRefFunction · 0.90
isFetchOptionsFunction · 0.85
setMethodFunction · 0.85
setTypeFunction · 0.85
executeFunction · 0.70

Tested by

no test coverage detected