Last active
January 12, 2023 07:33
-
-
Save stavros-melidoniotis/16ed104271bafd11d97423405181c908 to your computer and use it in GitHub Desktop.
React hook for performing fetch calls
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' | |
const useFetch = (url, options = {}) => { | |
const [loading, setLoading] = useState(true) | |
const [data, setData] = useState() | |
const [error, setError] = useState() | |
useEffect(() => { | |
const controller = new AbortController() | |
setLoading(true) | |
const fetchData = async () => { | |
try { | |
const res = await fetch(url, { | |
...options, | |
signal: controller.signal, | |
}) | |
const json = await res.json() | |
setData(json) | |
} catch (err) { | |
console.error(err) | |
setError(err) | |
} finally { | |
setLoading(false) | |
} | |
} | |
fetchData() | |
return () => { | |
controller.abort() | |
} | |
}, [url]) | |
return { loading, data, error } | |
} | |
export default useFetch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment