-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
index.tsx
55 lines (48 loc) · 1.32 KB
/
index.tsx
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
import { baseUrl } from "./baseUrl";
import { SWRConfig } from "swr";
import { WsProvider } from "./ws";
import axios from "axios";
import { ReactNode } from "react";
axios.defaults.baseURL = `${baseUrl}api/`;
type ApiProviderType = {
children?: ReactNode;
options?: Record<string, unknown>;
};
export function ApiProvider({ children, options }: ApiProviderType) {
axios.defaults.headers.common = {
"X-CSRF-TOKEN": 1,
"X-CACHE-BYPASS": 1,
};
return (
<SWRConfig
value={{
fetcher: (key) => {
const [path, params] = Array.isArray(key) ? key : [key, undefined];
return axios.get(path, { params }).then((res) => res.data);
},
onError: (error, _key) => {
if (
error.response &&
[401, 302, 307].includes(error.response.status)
) {
window.location.href =
error.response.headers.get("location") ?? "login";
}
},
...options,
}}
>
<WsWithConfig>{children}</WsWithConfig>
</SWRConfig>
);
}
type WsWithConfigType = {
children: ReactNode;
};
function WsWithConfig({ children }: WsWithConfigType) {
return <WsProvider>{children}</WsProvider>;
}
// eslint-disable-next-line react-refresh/only-export-components
export function useApiHost() {
return baseUrl;
}