-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseFetch.tsx
53 lines (49 loc) ยท 1.16 KB
/
useFetch.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
import { useEffect, useState } from "react";
interface RequestInit {
headers: any;
method: "PUT" | "POST" | "GET";
body: string;
}
export const useFetch = ({
url,
options,
control
}: {
url: string;
options: RequestInit;
control: {load:boolean,nomore:boolean}
}) => {
const [response, setResponse] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
const abortController = new AbortController();
const signal = abortController.signal;
const doFetch = async () => {
if(control.load)
setLoading(true);
if (control.nomore)
return null;
try {
const res = await fetch(url, { ...options, signal: signal });
const json = await res.json();
if (!signal.aborted) {
setResponse(json);
}
} catch (e) {
if (!signal.aborted) {
setError(e);
}
} finally {
if (!signal.aborted) {
setLoading(false);
}
}
};
doFetch();
return () => {
abortController.abort();
};
}, [options]);
return { response, error, loading };
};