JAVASCRIPT

Cancelling Pending API Requests with AbortController

Prevent memory leaks and unnecessary network activity in web applications by learning how to gracefully cancel in-flight API requests using the AbortController.

const abortController = new AbortController();
const signal = abortController.signal;

async function fetchDataAndCancel(url) {
  try {
    console.log('Fetching data...');
    const response = await fetch(url, { signal });
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log('Data fetched successfully:', data);
    return data;
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('Fetch aborted:', error.message);
    } else {
      console.error('Fetch error:', error);
    }
    throw error;
  }
}

// Example usage:
// Call the function
const promise = fetchDataAndCancel('https://api.example.com/data');

// Simulate cancelling after some time (e.g., component unmounts or user navigates away)
setTimeout(() => {
  abortController.abort();
  console.log('API request cancelled.');
}, 100); // Adjust delay as needed
How it works: The `AbortController` provides a way to cancel one or more DOM requests as and when desired. You create an `AbortController` instance and pass its `signal` property to the `fetch` request's options. When `abortController.abort()` is called, the associated `fetch` request is cancelled, and the promise returned by `fetch` rejects with an `AbortError`. This pattern is crucial for preventing memory leaks and unnecessary network activity in single-page applications, especially when components unmount before a fetch request completes.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs