AbortController (Cancel API request)

AbortController (Cancel API request)

What is Abort Controller?

Javascript web API has a method named as AbortController, that allows you to cancel one or more web API requests.

This AbortController has a property named signal which is used to create an abort signal that you can attach with your fetch request, which can be further used to abort that particular API request.

So to use this, first we will call an AbortController method

const contr = new AbortController();
const signal = controller.signal; //this is the signal which now can be attached to a fetch request to cancel it anytime

Below is the code for attaching the signal with the fetch API request

fetch("https://jsonplaceholder.typicode.com/todos/1", { signal })
        .then((response) => response.json())
        .then((json) => console.log(json))
        .catch((err) => console.log(err));

Now you might think that I have created an API request to get the result then why would I want to cancel it? If I have to cancel it then I will not call the API request in the first place.

Glad you asked it. So there might be some cases where you want to execute your API request but suddenly user has taken some action and now you don't want to execute that particular API. Let's understand this scenario with an example.

Why to cancel API request?

Let's say we have this feature in our web app, when we click on the First tab one API is called and when we click on the second tab another API is called.

This is the result of user action

In the above example, it is clearly visible that First Tab API takes some time to load the data. Till now everything seems to be correct now consider the below example

If a user switches to the Second tab before the API request is completed then there is a problem because after switching the tab, API request is completed therefore result of the first API is visible in the second tab. This is the behavior we don't want therefore abort controller exists.

After using AbortController, see the behavior

If a user switches the tab before the API request is completed then we have to abort the API request and we got the desired result.

Example

This is the example code for the above explanation, if you want then you can try the same in code sandbox. Although it is a React example but if you are a Javascript developer then you will get an idea of how it is working.

//APP.js

import { useState } from "react";
import "./styles.css";
import Tab1 from "./tab1";
import Tab2 from "./tab2";

export default function App() {
  const [tabClicked, setTabClicked] = useState("");
  const [result, setResult] = useState("");

  const tabClickedFun = (tab) => {
    setTabClicked(tab);
  };

  return (
    <div className="App">
      <div style={{ display: "flex" }}>
        <div
          onClick={() => tabClickedFun("first")}
          className={tabClicked === "first" ? "firstTab active" : "firstTab"}
        >
          First Tab
        </div>
        <div
          onClick={() => tabClickedFun("second")}
          className={tabClicked === "second" ? "secondTab active" : "secondTab"}
        >
          Second Tab
        </div>
      </div>
      {tabClicked === "first" ? (
        <Tab1 resultProp={(d) => setResult(d)} />
      ) : tabClicked === "second" ? (
        <Tab2 resultProp={(d) => setResult(d)} />
      ) : null}

      <div className="result">{result}</div>
    </div>
  );
}
//TAB1
import { useEffect } from "react";
import "./styles.css";

export default function Tab1({ resultProp }) {
  useEffect(() => {
    //Calling the AbortController method to get the signal property
    const controller = new AbortController();
    const signal = controller.signal;
    setTimeout(() => {
//Attaching the signal to the fetch request
      fetch("https://jsonplaceholder.typicode.com/todos/1", { signal     })
        .then((response) => response.json())
        .then((json) => resultProp("FIRST TAB"))
        .catch((err) => console.log(err));
    }, 1000);

    return () => {
    //Aborting the api request when component is unmounting
      controller.abort();
    };
  }, []);

  return <div className="Tab1"></div>;
}
//TAB2
import { useEffect} from "react";
import "./styles.css";

export default function Tab2({ resultProp }) {

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos/2")
      .then((response) => response.json())
      .then((json) => resultProp("SECOND TAB"));
  }, []);

  return (
    <div className="Tab2">
    </div>
  );
}

Hope you enjoyed reading, learning and implementing AbortController.

If you enjoyed then support by liking and commenting your views.

We will meet with another article, till then Goodbye and happy learning :-)

You can follow me on

LinkedIn - https://www.linkedin.com/in/prajwalbhatia/

Hashnode - https://prajwalbhatia.hashnode.dev/

Did you find this article valuable?

Support Prajwal Bhatia by becoming a sponsor. Any amount is appreciated!