Skip to content

Instantly share code, notes, and snippets.

@asaumet230
Last active April 15, 2022 15:22
Show Gist options
  • Save asaumet230/1e4f91446965a36cd60e503cc095db74 to your computer and use it in GitHub Desktop.
Save asaumet230/1e4f91446965a36cd60e503cc095db74 to your computer and use it in GitHub Desktop.
Custom Hook UseFetch( )
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