Skip to content

How to Cancel a Request in Axios

To cancel a request in Axios, you can use the CancelToken and cancel function provided by the axios library. Here’s an example of how to cancel a request:’

import axios from 'axios';

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

// Make a request using Axios
axios.get('/api/data', {
  cancelToken: cancelTokenSource.token
})
  .then(response => {
    // Process the response
    console.log(response.data);
  })
  .catch(error => {
    if (axios.isCancel(error)) {
      // Request was canceled
      console.log('Request canceled:', error.message);
    } else {
      // Handle other errors
      console.error('Error:', error.message);
    }
  });

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

In the example above:

  1. We import Axios library using the import statement.
  2. We create a cancel token source using axios.CancelToken.source().
  3. We make a GET request to /api/data and provide the cancelToken option with the cancel token from the source.
  4. If the request is successful, we process the response in the then block.
  5. If the request is canceled, Axios throws a Cancel error. We use axios.isCancel to check if the error is due to cancellation and handle it accordingly.
  6. If there’s an error other than cancellation, we handle it in the catch block.
  7. Finally, we cancel the request by calling cancel on the cancel token source and provide an optional cancellation message.

By canceling the request, any pending or ongoing network operations associated with it will be terminated, and the catch block will handle the cancellation error.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments