How to Fix AbortController for API Requests
DodaTech
Updated 2026-06-26
1 min read
The Problem
In this quick-fix, you'll learn how to use AbortController to cancel API requests on unmount. This matters because uncancelled requests waste bandwidth and cause state updates. In real-world applications, this pattern appears in search-as-you-type tab navigation data fetching components.
The Wrong Way
function SearchResults({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
fetch('/api/search?q='+query).then(r=>r.json()).then(setResults);
}, [query]);
return <div>...</div>;
}
If query changes before fetch completes stale data shown
The Right Way
function SearchResults({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
const c = new AbortController();
fetch('/api/search?q='+query, {signal:c.signal}).then(r=>r.json())
.then(setResults).catch(e => { if(e.name!=='AbortError') console.error(e); });
return () => c.abort();
}, [query]);
return <div>...</div>;
}
Previous fetch aborted on query change -- no stale state
Prevention
- Always use AbortController with fetch in useEffect
- Pass signal to fetch and abort on cleanup
- Check for AbortError in catch and ignore it
FAQ
This guide is brought to you by DodaTech -- built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
← Previous
React DnD Custom Preview Not Showing — Fix Drag Layer
Next →
How to Fix useEffect with Async/Await
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro