DEV Community

Hamza Ali
Hamza Ali

Posted on

Ensuring Data Consistency in Concurrent API Requests: Introducing the AbortController

Let's say you are working on a project and in that project you want to get the data of the user's friends. Let's say you requested to fetch the data of Adam's friends. But Adam has a lot of friends so the API request takes time to fetch the list of friends. Now before the API has responded you decided that you want to fetch the friend list of Eve and Eve's friend list is short so the API responded quickly with the friend list of Eve and now as the API responded you display the data on the screen. But wait what about the API request of Adam's friend's list? As the API call is in progress when this API is going to complete it will override the result of Eve's friend list and instead of showing the right data we will be displaying the data of Adam's friends instead of Eve's.

You see the bug in the above explanation. So to get rid of the bug we need to abort the API of Adam's friend list. There are many ways to achieve this but for this blog, I will cover the AbortController.

AbortController

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

We will use the AbortController in the use effect like this

useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;

fetch('my-resource', { signal })
  .then(res => res.json())
  .then(res => setFriendsList(res))
  .catch(console.log);

return () => controller.abort();
Enter fullscreen mode Exit fullscreen mode

}, []);

But how exactly this AbortController works?

When the abort method on the controller is called, the fetch operation and every subsequent then methods are discarded, and the catch method is executed.

If you are doing anything in the catch block, then you might need to add a new check to make sure that you set the errors in the right scenario. So to check if the API is aborted mid execution you can check if controller.abort.signal is set to true, If it is then the API is aborted mid-execution.

Happy hacking!

Top comments (0)