Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant cancel Axios post request via CancelToken

This code cancel GET requests but cant abort POST calls.
If i send GET requests first and i dont cancel them via abortAll method,they just finish by themselves this token cancel by itself and doesnt work on next requests? What am i missing? Thanks,John

import axios from 'axios'
class RequestHandler {

 constructor(){
  this.cancelToken = axios.CancelToken;
  this.source = this.cancelToken.source();
 }

 get(url,callback){

  axios.get(url,{
   cancelToken:this.source.token,
  }).then(function(response){

        callback(response.data);

    }).catch(function(err){

        console.log(err);

    })

 }

post(url,callbackOnSuccess,callbackOnFail){
 axios.post(url,{

        cancelToken:this.source.token,

    }).then(function(response){

        callbackOnSuccess(response.data);

    }).catch(function(err){

        callbackOnFail()

    })
}

abortAll(){

 this.source.cancel();
    // regenerate cancelToken
 this.source = this.cancelToken.source();

}

}
like image 233
Jan Ciołek Avatar asked Jun 30 '17 17:06

Jan Ciołek


1 Answers

Cancel previous Axios request on new request with cancelToken and source.

https://github.com/axios/axios#cancellation

 // cancelToken and source declaration

 const CancelToken = axios.CancelToken;
 let source = CancelToken.source();

 source && source.cancel('Operation canceled due to new request.');

 // save the new request for cancellation
 source = axios.CancelToken.source();

 axios.post(url, postData, {
     cancelToken: source.token
 })
 .then((response)=>{
     return response && response.data.payload);
 })
 .catch((error)=>{
     return error;
 });
like image 176
Amol Magar Avatar answered Oct 24 '22 17:10

Amol Magar