How to cancel API calls as an expert ðÿ˜ž | By Rully Saputra | April 2025
2 mins read

How to cancel API calls as an expert ðÿ˜ž | By Rully Saputra | April 2025


Photo by Luca Bravo on UNCLASH

This article will show you how to easily cancel your API call if necessary

Sometimes you need to cancel an API call, for example when the user interacts with your web page and the request is no longer necessary. If you let the API call, it will not break your site, but it will add unnecessary network traffic without benefiting the user.

To manage this, you can use a JavaScript API called AbortController. This API provides an interface that allows you to abandon one or more web requests.

You can create a new AbortController Object and attach its signal to your API call function. When you have to cancel the request, you can invoke the abort Method to stop the web demand.

THE AbortController is not limited to web requests. It can also be used to more effectively remove event listeners. Instead of calling removeEventListener Many times you can simply attach the signal to your addEventListener Then call abort When the component or the page has not mounted.

// React

useEffect(() => {
const ab = new AbortController();

window.addEventListener(
'scroll',
() => {
console.log('scroll');
},
{ signal: ab.signal }
);

window.addEventListener(
'click',
() => {
console.log('click');
},
{ signal: ab.signal }
);

return () => {
ab.abort();
};
}, []);

I strongly recommend that you use this API!

Result:

I also implemented here

import { useState, useRef, useEffect } from 'react';

function App() {
const [isLoading, setIsLoading] = useState(false);
const abortFetchRef = useRef(new AbortController());

const handleDownloadData = async () => {
try {
setIsLoading(true);
await fetch(' {
signal: abortFetchRef.current.signal,
});
} finally {
setIsLoading(false);
}
};

const handleCancelDownlaod = () => {
abortFetchRef.current.abort();
};

// for event listeners
useEffect(() => {
const ab = new AbortController();

window.addEventListener(
'scroll',
() => {
console.log('scroll');
},
{ signal: ab.signal }
);

window.addEventListener(
'click',
() => {
console.log('click');
},
{ signal: ab.signal }
);

return () => {
ab.abort();
};
}, []);
return isLoading ? (
<button onClick={handleCancelDownlaod}>Cancel download data</button>
) : (
<button onClick={handleDownloadData}>Download data</button>
);
}

export default App;

Conclusion

In summary, the cancellation of useless API calls is a simple but powerful way to optimize your web application. Using AbortController You can effectively stop API requests that are no longer necessary and reduce unnecessary network traffic. This approach not only improves user experience, but also improves the effectiveness of your application.



Grpahic Designer