-
Notifications
You must be signed in to change notification settings - Fork 2
/
useSWRAxios.ts
49 lines (43 loc) · 1.26 KB
/
useSWRAxios.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
import useSWR, { SWRConfiguration, SWRResponse } from 'swr';
import { AxiosResponse, AxiosError } from 'axios';
/* Inspired by SWR Example:
* https://github.com/vercel/swr/blob/main/examples/axios-typescript/libs/useRequest.ts
*/
interface Return<Data, Error>
extends Pick<
SWRResponse<AxiosResponse<Data>, AxiosError<Error>>,
'isValidating' | 'error' | 'mutate'
> {
data: Data | undefined;
response: AxiosResponse<Data> | undefined;
isLoading: boolean;
}
export interface Config<Data = unknown, Error = unknown>
extends Omit<
SWRConfiguration<AxiosResponse<Data>, AxiosError<Error>>,
'fallbackData'
> {
fallbackData?: Data;
}
export const useSWRAxios = <Data = unknown, Error = unknown>(
key: string | null /* 'null' to conditionally fetch data */,
axiosFetcher: (...args: any) => Promise<AxiosResponse<Data>>,
config: SWRConfiguration<AxiosResponse<Data>, AxiosError<Error>> = {}
): Return<Data, Error> => {
const {
data: response,
error,
isValidating,
mutate,
} = useSWR<AxiosResponse<Data>, AxiosError<Error>>(key, axiosFetcher, config);
const data = response && response.data;
const isLoading = !error && !data;
return {
data,
response,
error,
isValidating,
isLoading,
mutate,
};
};