Skip to content

Commit a343eac

Browse files
useFetch
0 parents  commit a343eac

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

useFetch.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { useState, useEffect } from 'react';
2+
3+
const useFetch = (url) => {
4+
const [data, setData] = useState(null);
5+
const [error, setError] = useState(null);
6+
const [isFetching, setIsFetching] = useState(false);
7+
8+
useEffect(() => {
9+
const run = async () => {
10+
try {
11+
setIsFetching(true);
12+
const resultJSON = await fetch(url);
13+
if (!resultJSON.ok) {
14+
throw new Error(`Error while searching. Url that's failing: ${resultJSON.url}`);
15+
}
16+
17+
const result = await resultJSON.json();
18+
setData(result);
19+
setIsFetching(false);
20+
} catch (error) {
21+
setError(error.message);
22+
setIsFetching(false);
23+
}
24+
};
25+
26+
run();
27+
}, [url]);
28+
29+
return {
30+
data,
31+
error,
32+
isFetching
33+
};
34+
};
35+
36+
export default useFetch;

0 commit comments

Comments
 (0)