Peakiq Blog
Effective Request Cancellation with Axios in JavaScript
Step-by-step guide to implementing request cancellation in JavaScript applications using Axios CancelTokens. Prevent race conditions and optimize API calls.
Editorial2 min read310 words
Key Points:
-
CancelTokens in Axios:
- Axios allows us to create CancelTokens using the
CancelToken.source()method. These tokens can be included in requests to enable cancellation.
- Axios allows us to create CancelTokens using the
-
Canceling Requests:
- To cancel a request, we call the
cancelfunction on the CancelToken source. This interrupts the ongoing request and triggers an Axios cancellation error.
- To cancel a request, we call the
-
Handling Cancellation Errors:
- When a request is canceled, Axios throws a specific error (e.g.,
CanceledError). It's essential to handle these errors gracefully in our code.
- When a request is canceled, Axios throws a specific error (e.g.,
-
Resetting CancelTokens:
- After canceling a request, we might need to reset the CancelToken source to make new requests. This involves creating a new CancelToken source to replace the canceled one.
-
Best Practices:
- Ensure that cancellation logic is triggered at appropriate points in your application.
- Implement robust error handling to handle cancellation errors and other potential issues.
- Double-check request configurations and network connectivity to troubleshoot any issues with canceled requests.
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.