Created
August 2, 2022 01:25
-
-
Save Cool-Runningz/ffd89dc86fa4f2e48b89365aba0643f2 to your computer and use it in GitHub Desktop.
This file contains 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, 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