MCPcopy Create free account
hub / github.com/ava/use-http / useFetch

Function useFetch

src/useFetch.ts:16–118  ·  view source on GitHub ↗
(arg1: useFetchArg1, arg2?: Options | RequestInit)

Source from the content-addressed store, hash-verified

14type useFetchArg1 = string | Options & RequestInit
15
16export function useFetch(arg1: useFetchArg1, arg2?: Options | RequestInit) {
17 const context = useContext(URLContext)
18 let url: string | null = context.url || null
19 let options = {} as { signal?: AbortSignal | null } & RequestInit
20 let onMount = false
21 let baseUrl = ''
22 let method = 'GET'
23
24 const handleOptions = (opts: Options & RequestInit) => {
25 if (true) {
26 // take out all the things that are not normal `fetch` options
27 // need to take this out of scope so can set the variables below correctly
28 let { url, onMount, timeout, baseUrl, ...rest } = opts
29 options = { signal: undefined, ...rest }
30 }
31 if (context.url) url = context.url
32 if (opts.url) url = opts.url || context.url
33 if (opts.onMount) onMount = opts.onMount
34 if (opts.method) method = opts.method
35 if (opts.baseUrl) baseUrl = opts.baseUrl
36 }
37
38 if (typeof arg1 === 'string') {
39 // if we have a default url from context, and
40 // arg1 is a string, we treat it as a relative route
41 url = context.url ? context.url + arg1 : arg1
42
43 if (arg2 && isObject(arg2)) handleOptions(arg2)
44 } else if (isObject(arg1)) {
45 handleOptions(arg1)
46 }
47
48 const [data, setData] = useState(null)
49 const [loading, setLoading] = useState(onMount)
50 const [error, setError] = useState(null)
51 const controller = useRef(null) as MutableRefObject<AbortController | null>
52
53 const fetchData = useCallback(
54 (method: string) => async (fArg1?: object | string, fArg2?: object | string) => {
55 if ('AbortController' in window) {
56 controller.current = new AbortController()
57 options.signal = controller.current.signal
58 }
59
60 let query = ''
61 // post | patch | put | etc.
62 if (isObject(fArg1) && method.toLowerCase() !== 'get') {
63 options.body = JSON.stringify(fArg1)
64 // relative routes
65 } else if (baseUrl && typeof fArg1 === 'string') {
66 url = baseUrl + fArg1
67 if (isObject(fArg2)) options.body = JSON.stringify(fArg2)
68 }
69 if (typeof fArg1 === 'string' && typeof fArg2 === 'string') query = fArg2
70
71 try {
72 setLoading(true)
73 const response = await fetch(url + query, {

Callers 9

useDeleteFunction · 0.85
useGetFunction · 0.85
usePatchFunction · 0.85
usePostFunction · 0.85
useQueryFunction · 0.85
usePutFunction · 0.85
useMutationFunction · 0.85
abort-examples.jsFile · 0.85

Calls 2

isObjectFunction · 0.85
handleOptionsFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…