Created
January 8, 2023 15:59
-
-
Save cakrads/9123120f8a265f1d39451f3f1105d94b to your computer and use it in GitHub Desktop.
Simple example how to implement abort controller in typescript react.js.
This file contains 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 } from "react"; | |
function Component() { | |
const abortControllerRef = useRef<AbortController>(new AbortController()); | |
const onAbortFetch = () => { | |
if (abortControllerRef.current) { | |
abortControllerRef.current.abort(); | |
console.log("Download aborted"); | |
// Reset new AbortController, so we can do re-fetch | |
abortControllerRef.current = new AbortController(); | |
} | |
}; | |
function getFile() { | |
const signal = abortControllerRef.current.signal; | |
fetch(API, { signal }) | |
.then((response) => { | |
console.log("Download complete", response); | |
}) | |
.catch((err) => { | |
if (err.name === "AbortError") { | |
console.log("successfully aborted"); | |
} else { | |
// handle error | |
} | |
}); | |
} | |
return ( | |
<> | |
<button onClick={getFile}>Get File</button> | |
<br /> | |
<br /> | |
<button onClick={onAbortFetch}>Abort</button> | |
</> | |
); | |
} | |
export default Component; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment