How to cancel Axios requests with cancel tokens
This small tip will show you how to utilize Axios cancelTokens to cancel ongoing requests.
Axios is a tiny javascript library for making Ajax requests. Sometimes you want to cancel a request before it finishes, here is how to do it.
let cancel; // This variable will hold the function which actually cancels the request, we leave it empty for now
let CancelToken = axios.CancelToken; // Initiate the cancelToken
axios.get('/some-route'), {
cancelToken: new CancelToken(function executor(cancelFunction) {
cancel = cancelFunction; // This is where we actually set the cancel variable to something useful
});
}).then((response) => {};
cancel(); // When you need to cancel your axios request, you can now call cancel() at any time in your code