I've read several similar questions, but I'm still struggling to be able to cancel my requests given my code structure.
On clicking one of the following elements I'd like to be able to cancel all other requests except the new one, however it seems to cancel all requests, and then prevents axios making any new ones. I'm new to cancelling tokens, so don't really know what I'm doing wrong here:
import {cancelTokenSource} from 'API';
let isActiveRequest;
document.body.addEventListener('click', async(e) => {
const userElement = e.target.closest('.user-element');
const appElement = e.target.closest('.app-element');
if(isActiveRequest) {
cancelTokenSource.cancel();
isActiveRequest = false;
}
if(userElement) {
isActiveRequest = true;
try{
const users = await Admin.getUsers();
isActiveRequest = false;
// display users
} catch(err) { isActiveRequest = false; }
}
if(appElement) {
isActiveRequest = true;
try{
const applications = await Admin.getApplications();
isActiveRequest = false;
// display applications
} catch(err) { isActiveRequest = false; }
}
});
API.js
export const cancelTokenSource = axios.CancelToken.source();
export default axios.create({
baseURL: 'http://localhost:8080',
cancelToken: cancelTokenSource.token
});
Admin.js
export default class Admin {
getUsers({index, limit, orderField, orderDirection}) {
return API.get('/admin/applicants', { params: { index, limit, orderField, orderDirection } });
}
getApplications({index, limit, orderField, orderDirection}) {
return JRS.get('/admin/applications', { params: { index, limit, orderField, orderDirection} });
...
}
Thanks
***Update
Thought maybe I need a new cancel token per request (as maybe it's the old token blocking any new requests), so tried this:
API.js
export let cancelTokenSource;
export default axios.create({
baseURL: 'http://localhost:8080',
cancelToken: new axios.CancelToken(c => cancelTokenSource = c),
});
main.js
if(isActiveRequest) {
cancelTokenSource();
isActiveRequest = false;
}
But no luck. I guess maybe because the instance of axios is the same for each request?
I'm going to try adding the cancel token to the Admin.js functions next