Last active
April 15, 2022 15:22
-
-
Save asaumet230/1e4f91446965a36cd60e503cc095db74 to your computer and use it in GitHub Desktop.
Custom Hook UseFetch( )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef, useState } from "react"; | |
const useFetch = (url) => { | |
const isMounted = useRef(true); //mantienes la referencia a la variable. | |
const [ state, setState ] = useState({ | |
data: null, | |
loading: true, | |
error: null | |
}); | |
useEffect(() => { | |
return () => { | |
isMounted.current = false; | |
} | |
}, [ ]) | |
useEffect(() => { | |
setState({ data: null , loading: true, error: null }); | |
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 información' | |
}); | |
}); | |
}, [ url ]) | |
return state; | |
} | |
export default useFetch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment