Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  43] [ 4]  / answers: 1 / hits: 13511  / 5 Years ago, tue, august 6, 2019, 12:00:00

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.


More From » vue.js

 Answers
28

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)
}
})
},

[#6668] Saturday, August 3, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hadens

Total Points: 142
Total Questions: 98
Total Answers: 100

Location: Kenya
Member since Mon, Jun 14, 2021
3 Years ago
;