Cant Cancel Axios Post Request Via CancelToken
Answer :
I have found out that you can cancel post request this way,i missunderstand this documentation part. In previous code,i have passed cancelToken to the POST data request not as a axios setting.
import axios from 'axios' var CancelToken = axios.CancelToken; var cancel; axios({ method: 'post', url: '/test', data: { firstName: 'Fred', lastName: 'Flintstone' }, cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter cancel = c; }) }).then(()=>console.log('success')).catch(function(err){ if(axios.isCancel(err)){ console.log('im canceled'); } else{ console.log('im server response error'); } }); // this cancel the request cancel()
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; });
Comments
Post a Comment