Skip to content

Instantly share code, notes, and snippets.

@cakrads
Created January 8, 2023 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cakrads/9123120f8a265f1d39451f3f1105d94b to your computer and use it in GitHub Desktop.
Save cakrads/9123120f8a265f1d39451f3f1105d94b to your computer and use it in GitHub Desktop.
Simple example how to implement abort controller in typescript react.js.
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