Peakiq Blog
17 December 2025

Key Points:
CancelTokens in Axios:
CancelToken.source() method. These tokens can be included in requests to enable cancellation.Canceling Requests:
cancel function on the CancelToken source. This interrupts the ongoing request and triggers an Axios cancellation error.Handling Cancellation Errors:
CanceledError). It's essential to handle these errors gracefully in our code.Resetting CancelTokens:
Best Practices:
Cancel.js
/* eslint-disable import/no-mutable-exports */
import axios from 'axios';
export let axiosCancelSource = axios.CancelToken.source();
export const resetCancelSource = (cancelMessage = 'Request is Cancelled') => {
axiosCancelSource.cancel(cancelMessage);
axiosCancelSource = axios.CancelToken.source();
};
DownloadClass
import axios from 'axios';
import { axiosCancelSource, resetCancelSource } from "../../../components/shared/cancelToken";
export class DownLoadAssessment {
static async DownloadMobileServer(ParamData) {
const { AxiosReqPayLoad } = ParamData;
try {
const response = await axios({
...AxiosReqPayLoad,
cancelToken: axiosCancelSource.token // Include cancel token from cancelToken.js file in request
});
return response.data;
} catch (error) {
if (axios.isCancel(error)) {
console.log('Request canceled:', error.message);
// Handle cancellation as needed
} else {
throw error; // Re-throw other errors
}
} finally {
// Reset the cancel token source after the request is completed
// use any where also
resetCancelSource();
}
}
}
Conclusion: Request cancellation is a powerful feature provided by Axios, allowing developers to manage asynchronous operations effectively. By understanding how to use CancelTokens and handle cancellation errors, developers can build more robust and responsive web applications.