I am using the abortcontroller to cancel a fetch request inside a custom react hook as shown below:
useEffect(() => {
const controller = new AbortController();
const { signal } = controller;
const fetchData = async () => {
try {
setState({ status: 'pending', data: null, error: null });
const response = await fetch(url, {
signal,
...options,
});
// if response is an HTTP error like 4XX 5XX
if (!response.ok) {
throw new Error(response.statusText);
}
// if response is 2XX
const data = (await response.json()) as T;
setState({ status: 'resolved', data, error: null });
} catch (error) {
setState({ status: 'rejected', data: null, error: error as Error });
}
};
fetchData();
return () => {
controller.abort(); // abort!
};
}, [url, options]);
Click to see live in CodeSandbox
When I try to hit multiple requests one after the other, I can see it cancels all my previous requests which is expected but when I revisit the same requests again there it doesn't cancel for the 2nd time.
We can see in the screenshot above while changing the IDs quickly using the up arrow from ID 10 to 24 we see all the intermediate requests are canceled successfully but when moving back using the down arrow, all the intermediate requests are hit and not canceled this time.