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
|
import { AxiosError, AxiosRequestConfig } from "axios";
import { useCallback, useReducer } from "react";
type StateType<T = any> = {
data: T | null;
loading: boolean;
error: AxiosError | null;
};
type ActionType<T> = {
type: string;
data?: T;
error?: AxiosError;
};
type Reducer<T = any> = (
state: StateType<T>,
action: ActionType<T>
) => StateType<T>;
const reducer: Reducer = (state, action) => {
switch (action.type) {
case "LOADING":
return {
data: null,
loading: true,
error: null,
};
case "SUCCESS":
return {
data: action.data as any,
loading: false,
error: null,
};
case "ERROR":
return {
data: null,
loading: false,
error: action.error as AxiosError,
};
default:
return state;
}
};
export type AsyncFc<TResult> = (
[...arg]: any[],
config: AxiosRequestConfig
) => Promise<TResult>;
const useAsync = <TResult>(
callback: AsyncFc<TResult>,
config: AxiosRequestConfig = {}
) => {
const [state, dispatch] = useReducer<Reducer<TResult>>(reducer, {
data: null,
loading: false,
error: null,
});
const run = useCallback(
async (...args) => {
dispatch({ type: "LOADING" });
try {
const data = await callback([...args], config);
dispatch({ type: "SUCCESS", data });
return data;
} catch (error) {
dispatch({ type: "ERROR", error });
}
},
[callback, config]
);
return { ...state, run };
};
export default useAsync;
|