DEV Community

Jamshdbek
Jamshdbek

Posted on

cancel request or abort token

Handling Canceled Requests in Axios and Fetch

Image description

const controller = new AbortController();

axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// cancel the request
controller.abort()
Enter fullscreen mode Exit fullscreen mode

When working with APIs, we often make GET requests to fetch data. Sometimes, these requests take longer to complete, and the user may navigate away from the page or initiate another action before the request completes. In such cases, the original request may still be in progress, leading to potential issues such as outdated or irrelevant data being displayed when the request finally completes. This can be particularly problematic for front-end developers who aim to provide a smooth user experience.

To address this issue, both Axios and the Fetch API in JavaScript offer mechanisms to cancel ongoing requests. This blog post will guide you through the steps to implement request cancellation using Axios and the Fetch API.

Canceling Requests with Axios
Axios provides a built-in way to cancel requests using the CancelToken source. Hereโ€™s how you can use it:
1.Install Axios if you haven't already:

npm install axios
Enter fullscreen mode Exit fullscreen mode

2.Create and cancel a request using CancelToken:

import axios from 'axios';

// Create a CancelToken source
const source = axios.CancelToken.source();

// Make a GET request with the cancel token
axios.get('https://api.example.com/data', {
  cancelToken: source.token
}).then(response => {
  console.log(response.data);
}).catch(error => {
  if (axios.isCancel(error)) {
    console.log('Request canceled:', error.message);
  } else {
    console.error('Error:', error);
  }
});

// Cancel the request
source.cancel('Request canceled by the user.');

Enter fullscreen mode Exit fullscreen mode

In this example, the request can be canceled by calling source.cancel().
Canceling Requests with Fetch
The Fetch API uses AbortController to handle request cancellations. Hereโ€™s how you can use it:
1.Create and cancel a request using AbortController:

// Create an AbortController instance
const controller = new AbortController();
const signal = controller.signal;

// Make a GET request with the signal
fetch('https://api.example.com/data', { signal })
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('Request canceled:', error.message);
    } else {
      console.error('Error:', error);
    }
  });

// Cancel the request
controller.abort();

Enter fullscreen mode Exit fullscreen mode

In this example, the request is canceled by calling controller.abort().

Conclusion
By using CancelToken in Axios and AbortController in the Fetch API, you can effectively manage and cancel ongoing requests, enhancing the user experience by ensuring that only relevant data is processed and displayed. This approach helps prevent potential issues that arise from outdated or unnecessary data being handled by your application.

happy coding ๐Ÿ˜„ "I hope this post was helpful!"

Top comments (0)