-
Notifications
You must be signed in to change notification settings - Fork 0
/
useFetch.js
38 lines (34 loc) · 1.02 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
import {useState , useEffect} from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [isPending, setisPending] = useState(true);
const[error,setError] = useState(null);
const abortcont = new AbortController();
useEffect(()=> {
setTimeout(() => {
fetch(url, { Signal:abortcont.signal })
.then(res => {
if(!res.ok){
throw Error('could not fetch the data ');
}
return res.json();
})
.then(data => {
setData(data);
setisPending(false);
setError(null);
})
.catch(err => {
if(err.name === 'AbortError'){
console.log('fetch aborted');
}else{
setisPending(false);
setError(err.message);
}
});
},1000);
return () => abortcont.abort();
} , [url]);
return {data, isPending, error};
}
export default useFetch;