forked from coldemo/gallery.code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseApi.ts
More file actions
72 lines (61 loc) · 1.76 KB
/
useApi.ts
File metadata and controls
72 lines (61 loc) · 1.76 KB
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
import Axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { useCallback, useState } from 'react';
interface PathParams {
[key: string]: string;
}
type Request = (
patch?: Partial<
AxiosRequestConfig & {
pathParams?: PathParams;
}
>
) => Promise<void>;
export interface UseApiObj<T = any, DT = T | null> {
request: Request;
error: Error | null;
response: AxiosResponse<T> | null;
getData: () => DT;
loading: boolean;
}
// @todo useMemo config / default
// @todo loading, error
let defaultParseData = (response: AxiosResponse | null) => {
return response ? response.data : null;
};
export let useApi = <T = any, DT = T>(
method: AxiosRequestConfig['method'],
urlPattern: string,
parseData: (response: AxiosResponse<T> | null) => DT = defaultParseData
): UseApiObj<T, DT> => {
let [response, setResponse] = useState<AxiosResponse<T> | null>(null);
let [loading, setLoading] = useState(false);
let [error, setError] = useState(null);
let request: Request = useCallback(
async (patch = {}) => {
let pathParams: PathParams = patch.pathParams || Object.create(null);
let trueUrl = urlPattern.replace(/\/:([^/?#&\d][^/?#&]*)/g, ($0, $1) => {
return `/${pathParams[$1]}`;
});
try {
setLoading(true);
let response = await Axios({
method,
url: trueUrl,
...patch,
});
setResponse(response);
setError(null);
} catch (err) {
setResponse(null);
setError(err);
} finally {
setLoading(false);
}
},
[method, setResponse, urlPattern]
);
let getData = useCallback(() => {
return parseData(response);
}, [parseData, response]);
return { request, error, response, getData, loading };
};