-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseFetch.ts
More file actions
33 lines (29 loc) · 808 Bytes
/
useFetch.ts
File metadata and controls
33 lines (29 loc) · 808 Bytes
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
import { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setTimeout(() => {
fetch(url)
.then(res => {
if (!res.ok) { // error coming back from server
throw Error('could not fetch the data for that city name');
}
return res.json();
})
.then(data => {
setIsPending(false);
setData(data);
setError(null);
})
.catch(err => {
// auto catches network / connection error
setIsPending(false);
setError(err.message);
})
}, 1000);
}, [url])
return { data, isPending, error };
}
export default useFetch;