-
-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathuseFetch.ts
167 lines (140 loc) · 4.78 KB
/
useFetch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import { useEffect, useState, useCallback, useRef } from 'react'
import {
HTTPMethod,
UseFetch,
ReqMethods,
Req,
Res,
UseFetchArrayReturn,
UseFetchObjectReturn,
UseFetchArgs
} from './types'
import { BodyOnly, FetchData, NoArgs } from './types'
import useFetchArgs from './useFetchArgs'
import useSSR from 'use-ssr'
import makeRouteAndOptions from './makeRouteAndOptions'
import { isEmpty, invariant } from './utils'
const makeResponseProxy = (res = {}) => new Proxy(res, {
get: (httpResponse: any, key) => (httpResponse.current || {})[key]
})
function useFetch<TData = any>(...args: UseFetchArgs): UseFetch<TData> {
const { customOptions, requestInit, defaults } = useFetchArgs(...args)
const {
url,
onMount,
onUpdate,
path,
interceptors,
timeout,
retries,
onTimeout,
onAbort,
} = customOptions
const { isServer } = useSSR()
const controller = useRef<AbortController>()
const res = useRef<Res<TData>>({} as Res<TData>)
const data = useRef<TData>(defaults.data)
const timedout = useRef(false)
const attempts = useRef(retries)
const [loading, setLoading] = useState(defaults.loading)
const [error, setError] = useState<any>()
const makeFetch = useCallback((method: HTTPMethod): FetchData => {
const doFetch = async (
routeOrBody?: string | BodyInit | object,
body?: BodyInit | object,
): Promise<any> => {
if (isServer) return // for now, we don't do anything on the server
controller.current = new AbortController()
controller.current.signal.onabort = onAbort
const theController = controller.current
setLoading(true)
setError(undefined)
let { route, options } = await makeRouteAndOptions(
requestInit,
method,
theController,
routeOrBody,
body,
interceptors.request,
)
const timer = timeout > 0 && setTimeout(() => {
timedout.current = true;
theController.abort()
onTimeout()
}, timeout)
let theData
let theRes
try {
theRes = ((await fetch(`${url}${path}${route}`, options)) || {}) as Res<TData>
try {
theData = await theRes.json()
} catch (err) {
theData = (await theRes.text()) as any // FIXME: should not be `any` type
}
theData = (defaults.data && isEmpty(theData)) ? defaults.data : theData
theRes.data = theData
res.current = interceptors.response ? interceptors.response(theRes) : theRes
invariant('data' in res.current, 'You must have `data` field on the Response returned from your `interceptors.response`')
data.current = res.current.data as TData
} catch (err) {
if (attempts.current > 0) return doFetch(routeOrBody, body)
if (attempts.current < 1 && timedout.current) setError({ name: 'AbortError', message: 'Timeout Error' })
if (err.name !== 'AbortError') setError(err)
} finally {
if (attempts.current > 0) attempts.current -= 1
timedout.current = false
if (timer) clearTimeout(timer)
controller.current = undefined
setLoading(false)
}
return data.current
}
return doFetch
}, [url, requestInit, isServer])
const post = makeFetch(HTTPMethod.POST)
const del = makeFetch(HTTPMethod.DELETE)
const request: Req<TData> = {
get: makeFetch(HTTPMethod.GET),
post,
patch: makeFetch(HTTPMethod.PATCH),
put: makeFetch(HTTPMethod.PUT),
del,
delete: del,
abort: () => controller.current && controller.current.abort(),
query: (query, variables) => post({ query, variables }),
mutate: (mutation, variables) => post({ mutation, variables }),
loading: loading as boolean,
error,
data: data.current,
}
const executeRequest = useCallback(() => {
const methodName = requestInit.method || HTTPMethod.GET
const methodLower = methodName.toLowerCase() as keyof ReqMethods
if (methodName !== HTTPMethod.GET) {
const req = request[methodLower] as BodyOnly
req(requestInit.body as BodyInit)
} else {
const req = request[methodLower] as NoArgs
req()
}
}, [requestInit.body, requestInit.method])
const mounted = useRef(false)
// handling onUpdate
useEffect((): void => {
if (onUpdate.length === 0 || !mounted.current) return
executeRequest()
}, [...onUpdate, executeRequest])
// handling onMount
useEffect((): void => {
if (mounted.current) return
mounted.current = true
if (!onMount) return
executeRequest()
}, [onMount, executeRequest])
return Object.assign<UseFetchArrayReturn<TData>, UseFetchObjectReturn<TData>>(
[request, makeResponseProxy(res), loading as boolean, error],
{ request, response: makeResponseProxy(res), ...request },
)
}
export { useFetch }
export default useFetch