Skip to content

Instantly share code, notes, and snippets.

@super-dog-human
Last active May 4, 2021 01:30
Show Gist options
  • Save super-dog-human/3939af97279ed76aed4ae1b817197e2b to your computer and use it in GitHub Desktop.
Save super-dog-human/3939af97279ed76aed4ae1b817197e2b to your computer and use it in GitHub Desktop.
fetch with timeout and aborting with using React hooks
import { useRef, useEffect } from 'react'
export default function useFetch() {
const abortsRef = useRef({})
function fetchFoo() {
return requestWithAbort(signal => fetch('/foo', { signal }))
}
function fetchBar() {
return requestWithAbort(signal => fetch('/bar', { signal }))
}
function requestWithAbort(request) {
const abortController = new AbortController()
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
abortsRef.current[timeout].abort()
delete abortsRef.current[timeout]
}, 1000 * 60)
abortsRef.current[timeout] = abortController
request(abortController.signal).then(r => {
resolve(r)
}).catch(e => {
reject(e)
}).finally(() => {
clearTimeout(timeout)
delete abortsRef.current[timeout]
})
})
}
useEffect(() => {
return () => {
Object.values(abortsRef.current).forEach(c => c.abort())
}
}, [])
return { fetchFoo, fetchBar }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment