-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseRequestWithPlaceholder.ts
77 lines (65 loc) · 1.71 KB
/
useRequestWithPlaceholder.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
import { useEffect, useReducer, type Reducer } from 'react'
interface DataFetcher<T> {
(): Promise<T>
}
type RequestState<T> = {
isLoading: boolean
isError: boolean
isSuccess: boolean
data: T
}
type RequestSuccessAction<T> = {
type: 'success'
data: T
}
type RequestErrorAction = {
type: 'error'
}
type RequestAction<T> = RequestErrorAction | RequestSuccessAction<T>
function requestReducer<T>(state: RequestState<T>, action: RequestAction<T>): RequestState<T> {
if (action.type === 'success') {
return {
isLoading: false,
isError: false,
isSuccess: true,
data: action.data,
}
} else {
return {
isLoading: false,
isError: true,
isSuccess: false,
data: state.data,
}
}
}
function getInitialState<T>(placeholder: T): RequestState<T> {
return {
isLoading: true,
isError: false,
isSuccess: false,
data: placeholder,
}
}
export function useRequestWithPlaceholder<T>(fn: DataFetcher<T>, placeholder: T) {
const [state, dispatch] = useReducer<Reducer<RequestState<T>, RequestAction<T>>>(
requestReducer,
getInitialState<T>(placeholder)
)
useEffect(() => {
async function fetchData() {
try {
const result = await fn()
dispatch({
type: 'success',
data: result
})
} catch (_e: unknown) {
dispatch({ type: 'error' })
}
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
fetchData()
}, [fn, dispatch])
return state
}