šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

What is the AbortController in Javascript and 4 ways to use it

The Javascript AbortController interface provides an elegant mechanism that allows us to abort different types of requests and async operations when needed.

AbortController works by adding its signal to an async operation so that later we can use it to cancel that operation:

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

waitAsyncStuff({ signal })

// later 
controller.abort()

Let's see some more hands-on examples.

1. Using AbortController to cancel fetch requests

Canceling fetch requests is maybe the main job of the AbortController:

const controller = new AbortController();
const {signal} = controller;

fetch(url, {signal})

// later
cancelBtn.onclick = ()=> controller.abort()

2. Using AbortController to remove Event Listeners

Using the AbortController also makes our life easier when we want to clean up Javascript event listeners.
Instead of keeping a manual reference to the action lister:

// with manual reference
const callback = ()=> { // do stuff here }
window.addEventListener = ('resize', callback)

// later, when we want to remove the event listener 
window.removeEventListener('resize', callback)

We can just do:

// with AbortController
const controller = new AbortController();
const {signal} = controller;
window.addEventListener = (
    'resize', 
    ()=> { // do stuff here }, 
    {signal}
)
// later
controller.abort()

Even if it's a bit more code, imagine that we can use the same AbortController with multiple Js action listeners.

3. Using AbortController to cancel the Javascript Eyedropper tool

You can use the AbortController also to cancel async operations of different UI tools such as the Javascript Eyedropper.

const eyeDropper = new EyeDropper();
const abortController = new AbortController();
// use abortController.abort() to programmatically close the eyeDropper

eyeDropper
    .open({ signal: abortController.signal })
    .then((result) => alert("Selected color: " + result.sRGBHex))

4. Using AbortController with React useEffect

This one is a bit more controversial, but we can use the AbortController in combination with the useEffect() React hook so that any pending request is canceled if that element is unmounted:

useEffect(() => {
  const controller = new AbortController();
  const signal = controller.signal;
  const results = [];
  const getPost = async (value) => {
    try {
      const response = await fetch(
        `https://jsonplaceholder.typicode.com/posts/${value}`,
        { signal }
      );
      results.push(`Success: ${value}`);
    } catch (error) {
      if (error.name === "AbortError") {
        results.push("API failure");
      }
    } finally {
      console.log("Status", results);
    }
  };

  getPost(1);

  return () => {
    // Cancel the request on unmount
    controller.abort();
  };
}, []);

Also we can use the AbortController to prevent mutiple fetch calls in useEffect() so that we can avoid race conditions.

I've found this talk by Simon Plenderleith to be quite a good resource for understanding how the AbortController works.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *