DEV Community

Cover image for Mastering Request Cancellation ❌ in JavaScript: Using AbortController with Axios and Fetch API.πŸš€πŸ’ͺ
Dharmendra Kumar
Dharmendra Kumar

Posted on

Mastering Request Cancellation ❌ in JavaScript: Using AbortController with Axios and Fetch API.πŸš€πŸ’ͺ

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.

const controller = new AbortController();
Enter fullscreen mode Exit fullscreen mode

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.

const signal = controller.signal;
Enter fullscreen mode Exit fullscreen mode

Instance Methods

abort()

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

controller.abort();
Enter fullscreen mode Exit fullscreen mode

Using AbortController with Fetch API

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

Example

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();
Enter fullscreen mode Exit fullscreen mode

Practical UI Code

<!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>
Enter fullscreen mode Exit fullscreen mode

Using AbortController with Fetch API

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

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();
Enter fullscreen mode Exit fullscreen mode

Practical UI Code

<!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>
Enter fullscreen mode Exit fullscreen mode

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!😊😊😊

Top comments (2)

Collapse
 
maldonadod profile image
Daniel Maldonado

Axios and Fetch API supports signal property, there are no difference.

Thanks for the post !

Collapse
 
dharamgfx profile image
Dharmendra Kumar

Hmm