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:
- We import Axios library using the
import
statement. - We create a cancel token source using
axios.CancelToken.source()
. - We make a GET request to
/api/data
and provide thecancelToken
option with the cancel token from the source. - If the request is successful, we process the response in the
then
block. - If the request is canceled, Axios throws a
Cancel
error. We useaxios.isCancel
to check if the error is due to cancellation and handle it accordingly. - If there’s an error other than cancellation, we handle it in the
catch
block. - 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.