I am trying to follow Axios documentation to cancel repeated requests to an URL but while I get no errors the requests aren't being cancelled. I still can do as many as I want through the following method.
import axios from 'axios'
getData({commit,state,dispatch}, id){
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios
.get("http://15.100.100.100:9999/getData/" + id,{
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
console.log("cancel error")
}
})
},
I followed Axios documentation found here https://github.com/axios/axios#cancellation
EDIT: Kaushik Makwana's answer was correct but in my case, instead of saving in a regular variable, i saved it in a state since my axios calls are made in my store.js file.
You can also cancel a request using a CancelToken. The axios cancel token API is based on the withdrawn cancelable promises proposal. You can create a cancel token using the CancelToken.
Cancel Fetch request If you want to cancel a Fetch request, you need to use the AbortController API. You can use the constructor to create a new AbortController object. It has a read-only property AbortController.
you can set a global variable to store past request.
var source;
getData({commit,state,dispatch}, id){
if(source){
source.cancel();
}
const CancelToken = axios.CancelToken;
source = CancelToken.source();
axios
.get("http://15.100.100.100:9999/getData/" + id,{
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
console.log("cancel error")
}
})
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With