How to Cancel API Request in React: Simple Guide
In React, you can cancel an API request by using the
AbortController API. Create an AbortController instance, pass its signal to the fetch request, and call abort() on the controller to cancel the request when needed.Syntax
Use the AbortController to create a controller object. Pass its signal property to the fetch request options. Call abort() on the controller to cancel the request.
- AbortController(): Creates a new controller.
- controller.signal: The signal to pass to fetch.
- controller.abort(): Cancels the request.
javascript
const controller = new AbortController(); fetch(url, { signal: controller.signal }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => { if (error.name === 'AbortError') { console.log('Request was cancelled'); } else { console.error('Fetch error:', error); } }); // To cancel the request: controller.abort();
Example
This React example shows how to cancel an API request when the component unmounts to prevent memory leaks and errors.
javascript
import React, { useEffect, useState } from 'react'; function UserData() { const [user, setUser] = useState(null); const [error, setError] = useState(null); useEffect(() => { const controller = new AbortController(); fetch('https://jsonplaceholder.typicode.com/users/1', { signal: controller.signal }) .then(response => response.json()) .then(data => setUser(data)) .catch(err => { if (err.name === 'AbortError') { console.log('Fetch aborted'); } else { setError('Failed to fetch user'); } }); return () => { controller.abort(); // Cancel fetch on unmount }; }, []); if (error) return <p>{error}</p>; if (!user) return <p>Loading user data...</p>; return ( <div> <h2>{user.name}</h2> <p>Email: {user.email}</p> </div> ); } export default UserData;
Output
<div>
<h2>Leanne Graham</h2>
<p>Email: Sincere@april.biz</p>
</div>
Common Pitfalls
- Not passing the
signalto the fetch request means you cannot cancel it. - Ignoring the
AbortErrorin the catch block can cause confusion. - Forgetting to abort the request on component unmount can cause memory leaks.
- Using cancellation with libraries like Axios requires their own cancellation tokens, not
AbortController.
javascript
/* Wrong: No signal passed, so abort won't work */ const controller = new AbortController(); fetch('https://api.example.com/data') // no signal .catch(console.error); // Right: Pass signal to fetch fetch('https://api.example.com/data', { signal: controller.signal }) .catch(error => { if (error.name === 'AbortError') { console.log('Request cancelled'); } });
Quick Reference
Steps to cancel API request in React:
- Create
AbortControllerinstance. - Pass
controller.signalto fetch options. - Call
controller.abort()to cancel. - Handle
AbortErrorin catch block. - Abort on component unmount to avoid leaks.
Key Takeaways
Use AbortController and pass its signal to fetch to enable cancellation.
Always abort fetch requests in useEffect cleanup to prevent memory leaks.
Handle the AbortError in catch to distinguish cancellations from other errors.
Axios and other libraries may require different cancellation methods.
Canceling requests improves app performance and user experience.