Contents of JavaScript

Essential JavaScript tips, tricks, and best practices to improve your coding skills and write more efficient code.

What happens when you abort an API request?

When you abort an API request, you're essentially canceling the request before it completes, typically to avoid unnecessary work or prevent side effects (like setting state on an unmounted component in React).

In modern JavaScript, especially with the Fetch API, this is commonly done using an AbortController.


πŸš€ How it works under the hood:

  1. AbortController creates a signal (AbortSignal) that is passed to the fetch request.
  2. If you call abort() on the controller:
    • The fetch is terminated immediately.
    • The Promise returned by fetch() is rejected with an error of type DOMException and the message "AbortError".
const controller = new AbortController(); fetch('/api/data', { signal: controller.signal }) .then(response => response.json()) .catch(error => { if (error.name === 'AbortError') { console.log('Request was aborted'); } else { console.error('Other error:', error); } }); controller.abort(); // Aborts the request

🌐 Browser Behavior:

  • The browser stops downloading the response body, freeing up memory and bandwidth.
  • The server might still process the request unless it supports abort/cancel from the client side (most don't).
  • If the request already completed before the abort, the abort() call has no effect.

βœ… Real-life Use Cases:

  1. Component Unmounting in React:

    • Prevents setting state after a component unmounts, avoiding memory leaks and warnings.
  2. Search Input / Autocomplete:

    • Abort previous requests as the user types, so only the latest result is shown.
  3. Timeouts / Performance Optimization:

    • Abort slow requests after a certain duration to keep the app responsive.

πŸ” What Doesn’t Happen:

  • No rollback or undo on the server β€” if the server has already processed the request, it won't know that the client aborted it.
  • In older APIs like XMLHttpRequest, aborting was also possible, but Fetch's AbortController is the modern and cleaner way.

🧠 Pro Tip:

If you're using tools like Axios, it also supports request cancellation via AbortController (in newer versions), or with a CancelToken in older versions.