/
usePromise.ts
181 lines (161 loc) · 4.35 KB
/
usePromise.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
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState, useMemo, useEffect, useRef } from 'react'
export type PromiseStatus = `pending` | `resolved` | `rejected`
export type CancelPromise = (message?: string) => void
export type ResetPromiseState<T> = (keys?: keyof PromiseState<T> | Array<keyof PromiseState<T>>) => void
export interface PromiseState<T> {
status?: PromiseStatus
promise?: Promise<T>
value?: Awaited<T>
error?: Error
cancel?: CancelPromise
}
export type PromiseStateWithReset<T> = PromiseState<T> & {
reset: ResetPromiseState<T>
}
/**
* A hook which accepts an asynchronous function (i.e., a function which returns a promise).
*
* Returns a new asynchronous function wrapping the original to be called as necessary,
* along with the state of the promise as `status`, `promise`, `value`, `error`, `cancel()`,
* and a `reset()` method to reset the state.
*
* Pairs well with the {@link hooks.useAsyncExtendedState | `useAsyncExtendedState`} hook.
*
* Example:
* ```ts
* interface State {
* foo: string
* bar: string
* }
*
* const [ state, setState, extendState ] = useAsyncExtendedState<State>({
* foo: 'foo',
* bar: 'bar'
* })
*
* const read = (id: string) => API.client.get<Partial<State>>(`things/${id}`).then(response => {
* return response.data
* })
*
* const [ readThingRequest, readThing ] = usePromise(read)
*
* const isPending = readThingRequest.status === 'pending'
*
* return (
* <>
* <div>
* foo: {state.foo}
* </div>
*
* <div>
* bar: {state.bar}
* </div>
*
* <UI.Button onClick={() => extendState(readThing('someId'))} disabled={isPending}>
* <span>
* {isPending
* ? 'Reading thing...'
* : 'Read thing'
* }
* </span>
* </UI.Button>
*
* <UI.Error>
* {readThingRequest.error}
* </UI.Error>
* </>
* )
* ```
*/
export const usePromise = <T extends (...args: any[]) => any>(
asyncFunction: T,
initialState?: PromiseState<ReturnType<T>>
): [
PromiseStateWithReset<ReturnType<T>>,
(...asyncFuncArgs: Parameters<T>) => ReturnType<T>
] => {
const [ state, setState ] = useState<PromiseState<ReturnType<T>>>(initialState || {})
const isUnmounted = useRef(false)
const callAsyncFunction = useMemo(() => (...args: Parameters<T>): ReturnType<T> => {
const promise = asyncFunction(...args)
let isCancelled = false
const cancel: CancelPromise = message => {
isCancelled = true
if (!isUnmounted.current) {
setState(({ value }) => ({
status: `rejected`,
value, error: message
? new Error(message)
: undefined
}))
}
}
if (promise instanceof Promise) {
return new Promise(resolve => {
const fulfillPromise = async () => {
try {
const value: Awaited<ReturnType<T>> = await promise
if (!isCancelled && !isUnmounted.current) {
setState({
status: `resolved`,
value
})
resolve(value)
}
} catch (error) {
if (!isCancelled && !isUnmounted.current) {
setState(({ value }) => ({
status: `rejected`,
value,
error: error instanceof Error
? error
: new Error(error as string)
}))
}
}
}
setState(({ value }) => ({
status: `pending`,
value,
promise,
cancel
}))
fulfillPromise()
}) as ReturnType<T>
} else {
setState({
status: `resolved`,
value: promise
})
return promise
}
}, [ asyncFunction ])
const reset = useMemo<ResetPromiseState<T>>(() => keys => setState(state => {
if (!keys) {
return {}
}
const nextState = { ...state }
if (Array.isArray(keys)) {
for (const key of keys) {
delete nextState[key]
}
} else {
delete nextState[keys]
}
return nextState
}), [])
const stateWithReset = useMemo<PromiseStateWithReset<ReturnType<T>>>(() => ({
...state,
reset
}), [
state,
reset
])
useEffect(() => {
return () => {
isUnmounted.current = true
}
}, [])
return [ stateWithReset, callAsyncFunction ]
}