Skip to content

Instantly share code, notes, and snippets.

@Cool-Runningz
Last active May 30, 2023 04:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cool-Runningz/22ddc174de688598fd938d8a81200652 to your computer and use it in GitHub Desktop.
Save Cool-Runningz/22ddc174de688598fd938d8a81200652 to your computer and use it in GitHub Desktop.
Async/await implementation of the useFetch hook
import { useEffect, useState } from "react";
const useFetchAsync = (initialUrl, options) => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [url, setUrl] = useState(initialUrl || "")
useEffect(() => {
if(!url) return
const fetchData = async () => {
setLoading(true)
try {
const response = await fetch(url, options)
if (!response.ok) {
throw new Error(`HTTP error status: ${response.status}`);
}
const json = await response.json()
setData(json)
setLoading(false)
setError(null)
} catch (error) {
//This catches the error if either of the promises fails or the manual error is thrown
setLoading(false)
setError(error.message)
}
}
fetchData()
}, [url, options]);
return [{ data, loading, error }, setUrl];
}
export default useFetchAsync;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment