Skip to content

Instantly share code, notes, and snippets.

@ercnshngit
Last active April 19, 2023 08:58
Show Gist options
  • Select an option

  • Save ercnshngit/5295a1f69c5de68a2c2da2b79f2d424b to your computer and use it in GitHub Desktop.

Select an option

Save ercnshngit/5295a1f69c5de68a2c2da2b79f2d424b to your computer and use it in GitHub Desktop.
just a basic fetching snippet with abort controller
import { useState, useEffect } from 'react'
export const useFetch = (url) => {
const [data, setData] = useState(null)
const [isPending, setIsPending] = useState(false)
const [error, setError] = useState(null)
useEffect(() => {
const controller = new AbortController()
const fetchData = async () => {
try {
setIsPending(true)
setData(null)
const res = await fetch(url, { signal: controller.signal })
if (!res.ok) throw new Error(res.statusText)
const json = await res.json()
setIsPending(false)
setData(json)
setError(null)
} catch(err) {
if (err.name === "AbortError") {
console.log("fetch was aborted")
} else {
setIsPending(false)
setError('Could not fetch the data')
}
}
}
fetchData()
return () => {
controller.abort()
}
}, [url])
console.log(data)
return { data, isPending, error }
}
export default useFetch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment