type MutableRefObject<T> = {
current: T | null; // generic type
};
const abortController: MutableRefObject<AbortController> = useRef(null);
const doRequest = () => {
abortController.current = new AbortController();
window
.fetch(url, {
method: 'GET',
signal: abortController.current.signal,
})
.then(res => res.json());
};
const cancelRequest = () => {
abortController.current?.abort(); // ? for Optional chaining
};
Basically the type of AbortController is AbortController . I created the type
MutableRefObject for useRef hook . The RefObject provided by React throws another error because the current property is readonly on RefObject .
type MutableRefObject<T> = {
current: T | null; // generic type
};
const abortController: MutableRefObject<AbortController> = useRef(null);
const doRequest = () => {
abortController.current = new AbortController();
window
.fetch(url, {
method: 'GET',
signal: abortController.current.signal,
})
.then(res => res.json());
};
const cancelRequest = () => {
abortController.current?.abort(); // ? for Optional chaining
};
Basically the type of AbortController is AbortController . I created the type
MutableRefObject for useRef hook . The RefObject provided by React throws another error because the current property is readonly on RefObject .
const abortController = useRef<AbortController>();
should work
TypeScript interface for abort signal not compatible with AbortController
AbortController.abort is missing parameter support
Videos
It's because you are missing the value DOM in the lib array of your tsconfig.json.
If you check the official repo, you will find the AbortController here!
export const activeControllers = new Set<AbortController>();
export const cancelAllRequests = () => {
activeControllers.forEach((controller) => controller.abort());
activeControllers.clear();
};
Prevent Memory Leaks: Cancels requests when components unmount to avoid memory issues
Save Resources: Stops unnecessary network calls and server load when not needed
Prevent Race Conditions: Ensures only the latest request data is used by cancelling old requests
Better UX: Makes the app more responsive by stopping outdated requests when user actions change