-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseFetch.js
42 lines (36 loc) · 1.03 KB
/
useFetch.js
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
import { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortCont = new AbortController();
setTimeout(() => {
fetch(url, { signal: abortCont.signal })
.then(res => {
if (!res.ok) { // error coming back from server
throw Error('could not fetch the data for that resource');
}
return res.json();
})
.then(data => {
setIsPending(false);
setData(data);
setError(null);
})
.catch(err => {
if (err.name === 'AbortError') {
console.log('fetch aborted')
} else {
// auto catches network / connection error
setIsPending(false);
setError(err.message);
}
})
}, 1000);
// abort the fetch
return () => abortCont.abort();
}, [url])
return { data, isPending, error };
}
export default useFetch;