Currently, I am working on implementing cancellation of axios calls in my project. After reviewing the axios documentation, it appears to be quite straightforward, which can be found here.
To begin, I have defined some variables at the top of my Vue component:
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
Of course, I have also included import axios from 'axios';
at the top.
Next, I have a method for fetching the API data. Within this method, I want to be able to cancel any ongoing requests, especially if a user is filtering multiple times in quick succession.
async fetchPartners(inputToClear) {
source.cancel();
...
try {
const response = await axios.get(`../partners?limit=1000${this.createRequestString()}`, {
cancelToken: source.token
});
// I have included the cancelToken in the request
this.partners = response.data.data;
} catch (error) {
if (axios.isCancel(error)) {
console.log('Request canceled', error.message);
}
const fetchErrors = this.utilGlobalHandleErrorMessages(error);
this.utilGlobalDisplayMessage(fetchErrors.message, { type: 'error' });
return [];
} finally {
...
}
},
Despite following the code example provided in the axios documentation, I am encountering an issue where the call is being cancelled before even making the request. The console displays:
Request canceled undefined
It appears as though the call is being cancelled before it is even initiated, despite calling source.cancel()
before the request. Any insights on this issue would be greatly appreciated.