Skip to main content

Using AbortController()

AbortController is a native JavaScript utility that allows developers to abort one or more ongoing web requests. It is especially useful in modern asynchronous applications to prevent unnecessary operations, improve performance, and avoid memory leaks.

When to use it:

  1. A user navigates away from a page
  2. A React component unmounts
  3. The user cancels an action manually
  4. A timeout threshold is reached

How to use it

  1. Create an Instance:

Start by creating an instance of AbortController:

const controller = new AbortController();
  1. Use signal in Fetch Requests:

When you make a fetch request (or use any other API that supports aborting), you pass the signal property of the AbortController instance in the request options. This signal is used to communicate with the request:

fetch(url, { signal: controller.signal });
  1. Abort the Request:

At any point after initiating the request, if you decide to abort the ongoing request, you can call the abort method on the AbortController instance. This sends a signal to the fetch request to terminate the operation:

controller.abort();
  1. Handling Abort Errors:

When a request is aborted, it throws an AbortError. You can catch this error in your catch block to handle the aborted request gracefully:

try {
await fetch(url, { signal: controller.signal });
} catch (error) {
if (error.name === "AbortError") {
// Request was intentionally aborted
} else {
// Handle other types of errors
}
}

Practical Use-Cases

React: Avoiding Memory Leaks:

When using fetch inside a useEffect, abort the request in the cleanup function to avoid setting state on an unmounted component.

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

const fetchData = async () => {
try {
const response = await fetch("/api/data", { signal: controller.signal });
// process response...
} catch (error) {
if (error.name === "AbortError") {
// Handle aborted request
}
}
};

fetchData();

return () => {
controller.abort(); // Cleanup
};
}, []);

User-Initiated Cancellation:

Let users cancel long-running operations like file uploads or fetch calls.

const handleCancelClick = () => {
controller.abort();
};

Custom Timeout Logic:

Manually abort a request if it exceeds a time threshold.

const controller = new AbortController();
setTimeout(() => controller.abort(), 5000); // 5-second timeout

Example of AbortController in a React Application:

AbortController provides a much-needed way to cancel fetch requests, which was not natively available in the early versions of the fetch API. This feature aligns well with the need for more control in asynchronous operations in modern web applications.

// Importing the Corva Data API client
import { corvaDataAPI } from "@corva/ui/clients";

// ...
// ...
// Initializing an AbortController instance
const controller = new AbortController();

// Defining an asynchronous function to fetch data
const fetchData = async () => {
try {
// Making a GET request to the Corva Data API with the AbortController signal
const response = await corvaDataAPI.get("/example.com", {
signal: controller.signal,
});
} catch (error) {
// Handling errors other than AbortError
if (error.name !== "AbortError") {
console.error("Hello, I canceled my request");
}
}
};

// Using the useEffect hook to fetch data and handle component unmount
useEffect(() => {
fetchData();

// Cleanup function to abort the fetch on component unmount or dependencies change
return () => {
controller.abort();
};
}, []);

// Function to handle click events and cancel the request
const handleCancelClick = () => {
// Cancel the ongoing request
controller.abort();
};