Skip to content

Instantly share code, notes, and snippets.

@Cool-Runningz
Created August 2, 2022 01:25
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/ffd89dc86fa4f2e48b89365aba0643f2 to your computer and use it in GitHub Desktop.
Save Cool-Runningz/ffd89dc86fa4f2e48b89365aba0643f2 to your computer and use it in GitHub Desktop.
import { useEffect, useState } from "react";
const useFetch = (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
setLoading(true)
fetch(url, options)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error status: ${response.status}`);
}
return response.json()
})
.then((json) => {
setData(json)
setLoading(false)
setError(null)
})
.catch(error => {
//This catches the error if either of the promises fail
setLoading(false)
setError(error.message)
})
}, [url, options]);
return [{ data, loading, error }, setUrl];
};
export default useFetch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment