Mastering Request Cancellation ❌ in JavaScript: Using AbortController with Axios and Fetch API.🚀💪
Tags: webdev, javascript, api, axios
Published: 2024-06-24 10:33:45

In modern web development, managing HTTP requests efficiently is crucial, especially when dealing with slow networks or potential duplicate requests. JavaScript's `AbortController` is a powerful tool for handling request cancellations. In this post, we will explore how to use `AbortController` with both Axios and the Fetch API.

## Why Use AbortController?

- **Efficiency**: Prevents unnecessary network requests and reduces server load.
- **User Experience**: Improves responsiveness by canceling outdated or duplicate requests.
- **Control**: Provides fine-grained control over request lifecycles, essential in complex applications.

### Where to Use AbortController?

- **Form Submissions**: Cancel previous requests when a user submits a new form.
- **Auto-Save**: Cancel ongoing save requests when new data is entered.
- **Search Functionality**: Cancel previous search queries when a new query is initiated.

## Understanding AbortController

### Constructor

The `AbortController` constructor creates a new `AbortController` object, which allows you to control the signal property to abort requests.

```javascript
const controller = new AbortController();
```

### Instance Properties

#### signal

The `signal` property of an `AbortController` instance is an `AbortSignal` object that can be used to communicate with the request and tell it to abort.

```javascript
const signal = controller.signal;
```

### Instance Methods

#### abort()

The `abort()` method of an `AbortController` instance is used to abort one or more web requests.

```javascript
controller.abort();
```

## Using AbortController with Fetch API

The Fetch API natively supports `AbortController`. Here's how to use it:

### Example

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

fetch('https://jsonplaceholder.typicode.com/posts', { signal })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('Fetch aborted');
    } else {
      console.error('Fetch error:', error);
    }
  });

// To abort the fetch request
controller.abort();
```

### Practical UI Code

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Fetch API with AbortController</title>
  <script defer src="app.js"></script>
</head>
<body>
  <button id="fetch-button">Fetch Data</button>
  <pre id="output"></pre>

  <script>
    const fetchButton = document.getElementById('fetch-button');
    const output = document.getElementById('output');
    let controller;

    fetchButton.addEventListener('click', () => {
      // Abort any previous request if it exists
      if (controller) {
        controller.abort();
      }

      // Create a new AbortController instance for the new request
      controller = new AbortController();
      const signal = controller.signal;

      // Make the fetch request with the signal
      fetch('https://jsonplaceholder.typicode.com/posts', { signal })
        .then(response => response.json())
        .then(data => output.textContent = JSON.stringify(data, null, 2))
        .catch(error => {
          // Handle the abort error specifically
          if (error.name === 'AbortError') {
            output.textContent = 'Fetch aborted';
          } else {
            console.error('Fetch error:', error);
          }
        });
    });
  </script>
</body>
</html>
```

![Using AbortController with Fetch API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b9cc93dzhbqh8mt13h5h.png)


### Explanation

1. **HTML Structure**: 
   - A button to initiate the fetch request.
   - A `<pre>` element to display the output.

2. **JavaScript Code**: 
   - **Elements and Controller**: References to the button and output elements are created. A variable `controller` is declared to hold the `AbortController` instance.
   - **Event Listener**: The button has an event listener for the 'click' event.
     - **Abort Previous Request**: If there is an existing `controller`, its `abort()` method is called to cancel the ongoing request.
     - **Create New Controller**: A new `AbortController` instance is created, and its `signal` is used in the new request.
     - **Make Request**: The request is made using the Fetch API, passing the `signal`.
     - **Handle Response and Errors**: The response is handled by converting it to JSON and displaying it. Errors are caught and handled. If the error is due to the request being aborted, a specific message is displayed.

## Using AbortController with Axios

Axios does not support `AbortController` natively but allows similar functionality through cancellation tokens.

### Example

```javascript
const axios = require('axios');

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

axios.get('https://jsonplaceholder.typicode.com/posts', { signal })
  .then(response => console.log(response.data))
  .catch(error => {
    if (axios.isCancel(error)) {
      console.log('Request canceled', error.message);
    } else {
      console.error('Request error:', error);
    }
  });

// To cancel the request
controller.abort();
```

### Practical UI Code

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Axios with AbortController</title>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script defer src="app.js"></script>
</head>
<body>
  <button id="axios-fetch-button">Fetch Data</button>
  <pre id="axios-output"></pre>

  <script>
    const fetchButton = document.getElementById('axios-fetch-button');
    const output = document.getElementById('axios-output');
    let controller;

    fetchButton.addEventListener('click', () => {
      // Abort any previous request if it exists
      if (controller) {
        controller.abort();
      }

      // Create a new AbortController instance for the new request
      controller = new AbortController();
      const signal = controller.signal;

      // Make the axios request with the signal
      axios.get('https://jsonplaceholder.typicode.com/posts', { signal })
        .then(response => output.textContent = JSON.stringify(response.data, null, 2))
        .catch(error => {
          // Handle the cancel error specifically
          if (axios.isCancel(error)) {
            output.textContent = 'Request canceled';
          } else {
            console.error('Request error:', error);
          }
        });
    });
  </script>
</body>
</html>
```

### Explanation

1. **HTML Structure**:
   - A button to initiate the fetch request.
   - A `<pre>` element to display the output.

2. **JavaScript Code**:
   - **Elements and Controller**: References to the button and output elements are created. A variable `controller` is declared to hold the `AbortController` instance.
   - **Event Listener**: The button has an event listener for the 'click' event.
     - **Abort Previous Request**: If there is an existing `controller`, its `abort()` method is called to cancel the ongoing request.
     - **Create New Controller**: A new `AbortController` instance is created, and its `signal` is used in the new request.
     - **Make Request**: The request is made using Axios, passing the `signal`.
     - **Handle Response and Errors**: The response is handled by converting it to JSON and displaying it. Errors are caught and handled. If the error is due to the request being aborted, a specific message is displayed.

### Practical Application

These examples demonstrate how to handle request cancellations in real-world scenarios:
- **Fetch Data Button**: When the "Fetch Data" button is clicked multiple times, any ongoing request is aborted before starting a new one. This ensures that only the most recent request is processed, improving efficiency and user experience.
- **Output Display**: The results are displayed in the `<pre>` element, allowing users to see the fetched data or any errors.

##Conclusion
By leveraging AbortController with both the Fetch API and Axios, you can significantly improve the efficiency and responsiveness of your web applications. This approach ensures better control over network requests, resulting in enhanced user experiences and optimized resource utilization. Happy coding!😊😊😊