Skip to content

Instantly share code, notes, and snippets.

@stavros-melidoniotis
Last active January 12, 2023 07:33
Show Gist options
  • Save stavros-melidoniotis/16ed104271bafd11d97423405181c908 to your computer and use it in GitHub Desktop.
Save stavros-melidoniotis/16ed104271bafd11d97423405181c908 to your computer and use it in GitHub Desktop.
React hook for performing fetch calls
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