API requests and AbortController in JS...

One of the repeated tasks for a Frontend dev is to fetch a data from the server using an API. There are two popular libraries which will solve the problem, namely Axios and Fetch(Not an additional package).

Though, fetching the data is an easy part. It is important to fetch the data in clean and professional way. Recently, I came across an interface called AbortController. In this post, let us take a look on how can we use the interface to make efficient API calls.

Let's say there is an endpoint namely /user/{user-id}. Whenever my website renders a particular user page, my app will call the endpoint with the user-id in the URL and use the response to render the UI accordingly. This is the common way for retrieving and rendering the data.

Now, there can be two problems. What if the endpoint which we use returns a huge payload? Secondly, what if my network is very slow? How can we minimise the wastage of requests?

Let's say we are having a component called user. Based on the user-id(we will assume it as 2) in the URL, the component will query the endpoint and render the user's data. If my network is slow and payload is high, the response turn around time will be significant. Meanwhile, I might be navigating to another user-id page, let's assume it to be 3.

Totally, there will be two requests now. One is for the user-id with an ID of 2 and another with an ID of 3. If we notice, we already navigated to the user with an ID of 3, how can we cancel or ignore the request for the user, whose ID is 2.

That's where the AbortController kicks in.

"The AbortController interface represents a controller object that allows you to abort one or more Web requests as and when desired." ---MDN

Before making an API call, we will create a controller instance from the Interface. This instance will have access to two most important attributes named signal and abort. We will pass the signal attribute to the Fetch request as an additional option. On the other hand, we will abort the request using the abort attribute in the cleanup function. The sample implementation will be React based for the sake of this post.

const User = ({userId}) => {
  const userUrl = `/user/${userId}`;  
  useEffect(()=>{
    const controller = new AbortController();
    const signal = controller.signal;
    fetch(userUrl, {signal})
    .then((res)=>res.json())
    .then((user)=>{
      console.log("user data", user);
    })
   .catch((err)=>{
      if(err === "AbortError"){
        console.log("user aborted the request");
      }
      else{
        /* Handle the error */
      }
   })
    return ()=>controller.abort();
  }, [
    //Dependencies if any
  ])
  return (
    {/* user data to be rendered */}
  )
}

export default User;

To be noted that, error called because of abortController will have AbortError as its message.

Happy coding!!!

Feel free to give some comments regarding the quality of post. I will work on it and improve.