-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
299 lines (273 loc) · 7.54 KB
/
index.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import { useLatest } from '../use-latest'
import { useMount } from '../use-mount'
import { useStableFn } from '../use-stable-fn'
import { useTrackedRefState } from '../use-tracked-ref-state'
import { useUnmount } from '../use-unmount'
import { useVersionedAction } from '../use-versioned-action'
import { isFunction } from '../utils/basic'
import type { AnyFunc, Gettable, Promisable } from '../utils/basic'
export interface UseAsyncFnOptions<T extends AnyFunc, D = Awaited<ReturnType<T>>, E = any> {
/**
* Initial data to be used as the initial value
*
* @defaultValue undefined
*
* @since 1.4.0
*/
initialValue?: D
/**
* Initial parameters passed to fetcher when first mount
*
* @defaultValue []
*
* @since 1.4.0
*/
initialParams?: Gettable<Promisable<Parameters<T> | []>>
/**
* whether to run the async function immediately on component mount
*
* @defaultValue false
*
* @since 1.4.0
*/
immediate?: boolean
/**
* whether to clear the value before running the function
*
* @defaultValue false
*/
clearBeforeRun?: boolean
/**
* whether to cancel the async function when the component is unmounted
*
* @defaultValue true
*
* @since 1.4.0
*/
cancelOnUnmount?: boolean
/**
* a function to run when the async function throws an error
*
* @defaultValue undefined
*
* @since 1.4.0
*/
onError?: (error: E | undefined) => void
/**
* a function to run before the async function
*
* @defaultValue undefined
*
* @since 1.4.0
*/
onBefore?: (value: D | undefined, params: Parameters<T> | []) => void
/**
* a function to run after the async function
*
* @defaultValue undefined
*
* @since 1.4.0
*/
onSuccess?: (value: D, params: Parameters<T> | []) => void
/**
* a function to run after the async function
*
* @defaultValue undefined
*
* @since 1.4.0
*/
onFinally?: (value: D | undefined, params: Parameters<T> | []) => void
/**
* a function to run when the async function is cancelled
*
* @defaultValue undefined
*
* @since 1.4.0
*/
onCancel?: (value: D | undefined, params: Parameters<T> | []) => void
/**
* a function to run when the value is mutated
*
* @defaultValue undefined
*
* @since 1.4.0
*/
onMutate?: (value: D | undefined, params: Parameters<T> | []) => void
/**
* a function to run when the value is refreshed
*
* @defaultValue undefined
*
* @since 1.4.0
*/
onRefresh?: (value: D | undefined, params: Parameters<T> | []) => void
/**
* Custom cache comparison function, `true` means the cache is the same
*
* @defaultValue shallowEqual
*
* @since 1.4.0
*/
compare?: (prevData: D | undefined, nextData: D | undefined) => boolean
}
export type UseAsyncFnMutateAction<D, P> =
| [D | undefined]
| [D | undefined, P | undefined]
| [(prevData: D | undefined, preParams?: P) => [D, P | undefined]]
export interface UseAsyncFnReturns<T extends AnyFunc, D = Awaited<ReturnType<T>>, E = any> {
/**
* a function to run the async function
*/
run: T
/**
* a function to refresh the async function
*/
refresh: (params?: Parameters<T> | []) => Promise<D | undefined>
/**
* a function to cancel the async function
*/
cancel: () => void
/**
* manually set the value
*/
mutate: (...actions: UseAsyncFnMutateAction<D | undefined, Parameters<T> | []>) => void
/**
* whether the async function is loading
*/
loading: boolean
/**
* the error thrown by the async function
*/
error: E | undefined
/**
* the value returned by the async function
*/
value: D | undefined
/**
* the parameters passed to the async function
*/
params: Parameters<T> | []
}
export function resolveMutateActions<D, P>(actions: UseAsyncFnMutateAction<D, P>, prevData: D, prevParams: P): [D, P] {
return (isFunction(actions[0]) ? actions[0](prevData, prevParams) : (actions as [D, P])) as [D, P]
}
/**
* A React Hook to run **async** functions with extra **loading** state that indicates whether the promise is pending.
*
* @param {AnyFunc} fn - `AnyFunc`, the async function to run, see {@link AnyFunc}
* @returns {UseAsyncFnReturns} `UseAsyncFnReturns`, see {@link UseAsyncFnReturns}
*/
export function useAsyncFn<T extends AnyFunc, D = Awaited<ReturnType<T>>, E = any>(
fn: T,
options: UseAsyncFnOptions<T, D, E> = {},
): UseAsyncFnReturns<T, D, E> {
const {
initialParams = [],
immediate = false,
clearBeforeRun = false,
cancelOnUnmount = true,
compare,
onError,
onMutate,
onRefresh,
onCancel,
onBefore,
onSuccess,
onFinally,
} = options
const [incVersion, runVersionedAction] = useVersionedAction()
const [refState, actions, stateRef] = useTrackedRefState({
error: undefined as E | undefined,
loading: Boolean(immediate),
value: options.initialValue,
params: [] as Parameters<T> | [],
})
const latest = useLatest({
fn,
clearBeforeRun,
cancelOnUnmount,
onMutate,
onCancel,
onRefresh,
onError,
onBefore,
onSuccess,
onFinally,
compare,
})
const cancel = useStableFn(() => {
incVersion()
actions.updateRefState('loading', false)
latest.current.onCancel?.(stateRef.value.value, stateRef.params.value)
})
const run = useStableFn(async (...args: Parameters<T> | []) => {
actions.updateRefState('params', args)
const version = incVersion()
let result: D | undefined = undefined
try {
latest.current.onBefore?.(stateRef.value.value, stateRef.params.value)
if (latest.current.clearBeforeRun) {
actions.updateRefState('value', undefined)
}
actions.updateRefState('loading', true)
result = await latest.current.fn(...args)
runVersionedAction(version, () => {
latest.current.onSuccess?.(result as D, stateRef.params.value)
actions.updateRefState('value', result, latest.current.compare)
actions.updateRefState('error', undefined)
})
} catch (error) {
runVersionedAction(version, () => {
latest.current.onError?.(error as E | undefined)
actions.updateRefState('error', error as E | undefined)
})
} finally {
runVersionedAction(version, () => {
latest.current.onFinally?.(result, stateRef.params.value)
actions.updateRefState('loading', false)
})
}
return result
}) as T
const mutate = useStableFn((...mutateActions: UseAsyncFnMutateAction<D | undefined, Parameters<T> | []>) => {
const [nextValue, nextParams] = resolveMutateActions<D | undefined, Parameters<T> | []>(
mutateActions,
stateRef.value.value,
stateRef.params.value,
)
actions.updateRefState('value', nextValue)
actions.updateRefState('params', nextParams)
latest.current.onMutate?.(nextValue, nextParams ?? [])
})
const refresh = useStableFn(async (params?: Parameters<T> | []) => {
const actualParams = (params ?? stateRef.params.value) || []
const result = await run(...actualParams)
latest.current.onRefresh?.(result, actualParams)
return result
})
useMount(async () => {
if (immediate) {
const params = await (initialParams instanceof Function ? initialParams() : initialParams)
await run(...params)
}
})
useUnmount(cancelOnUnmount && cancel)
return {
run,
refresh,
mutate,
cancel,
get loading() {
return refState.loading
},
get error() {
return refState.error
},
get value() {
return refState.value
},
get params() {
return refState.params
},
}
}