Last active
May 4, 2021 01:30
-
-
Save super-dog-human/3939af97279ed76aed4ae1b817197e2b to your computer and use it in GitHub Desktop.
fetch with timeout and aborting with using React hooks
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 { 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