Last active
February 6, 2024 22:33
-
-
Save jonmircha/11b1d5cd82474fc6c79f03836410b243 to your computer and use it in GitHub Desktop.
Hook personalizado en React para manipular peticiones Fetch y guardarlas en variables de estado
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 { useState, useEffect } from "react"; | |
export const useFetch = (url) => { | |
const [data, setData] = useState(null); | |
const [error, setError] = useState(null); | |
const [loading, setLoading] = useState(false); | |
useEffect(() => { | |
const abortController = new AbortController(); | |
const signal = abortController.signal; | |
const fetchData = async () => { | |
setLoading(true); | |
try { | |
const res = await fetch(url, { signal }); | |
if (!res.ok) { | |
let err = new Error("Error en la petición Fetch"); | |
err.status = res.status || "00"; | |
err.statusText = res.statusText || "Ocurrió un error"; | |
throw err; | |
} | |
const json = await res.json(); | |
if (!signal.aborted) { | |
setData(json); | |
setError(null); | |
} | |
} catch (error) { | |
if (!signal.aborted) { | |
setData(null); | |
setError(error); | |
} | |
} finally { | |
if (!signal.aborted) { | |
setLoading(false); | |
} | |
} | |
}; | |
fetchData(); | |
return () => abortController.abort(); | |
}, [url]); | |
return { data, error, loading }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment