File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
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 ;
You can’t perform that action at this time.
0 commit comments