-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
useFetch.ts
64 lines (56 loc) 路 2 KB
/
useFetch.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
import { useEffect, useState } from "react";
import { useSupabase } from "@/lib/context/SupabaseProvider";
interface FetchInstance {
get: (url: string, headers?: HeadersInit) => Promise<Response>;
post: (
url: string,
body: BodyInit | null | undefined,
headers?: HeadersInit
) => Promise<Response>;
put: (
url: string,
body: BodyInit | null | undefined,
headers?: HeadersInit
) => Promise<Response>;
delete: (url: string, headers?: HeadersInit) => Promise<Response>;
}
const fetchInstance: FetchInstance = {
get: async (url, headers) => fetch(url, { method: "GET", headers }),
post: async (url, body, headers) =>
fetch(url, { method: "POST", body, headers }),
put: async (url, body, headers) =>
fetch(url, { method: "PUT", body, headers }),
delete: async (url, headers) => fetch(url, { method: "DELETE", headers }),
};
export const useFetch = (): { fetchInstance: FetchInstance } => {
const { session } = useSupabase();
const [instance, setInstance] = useState(fetchInstance);
const baseURL = `${process.env.NEXT_PUBLIC_BACKEND_URL ?? ""}`;
const backendUrl = baseURL;
useEffect(() => {
setInstance({
...fetchInstance,
get: async (url, headers) =>
fetchInstance.get(`${backendUrl}${url}`, {
Authorization: `Bearer ${session?.access_token ?? ""}`,
...headers,
}),
post: async (url, body, headers) =>
fetchInstance.post(`${backendUrl}${url}`, body, {
Authorization: `Bearer ${session?.access_token ?? ""}`,
...headers,
}),
put: async (url, body, headers) =>
fetchInstance.put(`${backendUrl}${url}`, body, {
Authorization: `Bearer ${session?.access_token ?? ""}`,
...headers,
}),
delete: async (url, headers) =>
fetchInstance.delete(`${backendUrl}${url}`, {
Authorization: `Bearer ${session?.access_token ?? ""}`,
...headers,
}),
});
}, [session, backendUrl]);
return { fetchInstance: instance };
};