-
Notifications
You must be signed in to change notification settings - Fork 0
/
useFetch.js
44 lines (33 loc) · 1.06 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
43
44
import { useState, useEffect, useRef } from 'react';
export const useFetch = ( url ) => {
const isMounted = useRef(true);
const [state, setState] = useState({data: null, loading: true, error: null});
useEffect(() => {
return () => {
isMounted.current = false;
}
}, [])
useEffect(() => {
setState({ data: null, loading: true, error: null });
//esto se hace para que cuando apriete el boto aparezca denuevo 'loading...'
fetch(url)
.then( resp => resp.json() )
.then( data => {
if( isMounted.current ) {
setState({
loading: false,
error: null,
data
});
}
})
.catch( () => {
setState({
data: null,
loading: false,
error: 'No se pudo cargar la info'
})
})
}, [ url ])
return state;
}