Reputation: 741
Axios cancel Request shows browser alert which stops the execution until you click ok. I want to cancel my requests, all my Api calls are in separate file named apiCalls.js.
Component with cancelToken.
componentDidMount() {
const CancelToken = axios.CancelToken;
// create the source
this.source = CancelToken;
}
persistCancel = (cancel) => {
this.setState({cancels: [...this.state.cancels, cancel]})
}
componentWillUnmount(){
this.state.cancels.forEach((c) => c());
}
this is my Api call from component.
getScoreCardCall({profileId, campaignIds, startDate, endDate}, (scoreCards) => {
//success
this.setState({
scoreCards,
showComcardsLoader: false
})
},this.source,this.persistCancel);
and in the apiCalls.js
export function getScoreCardCall(params,callback, source,onRequest){
axios.get(url,
{
cancelToken: new source(function executor(c) {
onRequest(c);
}),
params:{
profileId: params.profileId,
campaignId: params.campaignIds.toString(),
startDate: params.startDate,
endDate: params.endDate,
}
})
.then(res => {
if(callback != null){
if(res.data.length!=0){
callback(res.data);
}
}
})
.catch(err => {
if (axios.isCancel(err)) {
console.log(err.message);
}
})
}
Can someone please tell me why is alert showing with every request cancellation?? or what i am doing wrong?
Upvotes: 0
Views: 592
Reputation: 320
axios#cancellationdescribes two ways to use the cancelToken. You used the first way, with source.token/source.cancel. I started out that way, and had a similar problem as yours: Once a request to a particular URL was canceled, I could never get a successful response from that URL again. I switched to the second method using an executor function and the problem went away. I guess was sharing the same cancelToken for multiple requests, which is what they say you can do with the executor function method. Anyway, maybe that would work for you too.
Upvotes: 1