I am using axios
and vue.js
.I have google it,and check the axios docs but still cannot understand how to do it.
2020 UPDATE: How to cancel an axios request
cancelToken
and store itimport axios from 'axios'
const request = axios.CancelToken.source();
cancelToken
to the axios requestaxios.get('API_URL', { cancelToken: request.token })
.cancel()
method to cancel itrequest.cancel("Optional message");
See it live on a tiny app on codesandbox
Take a look at axios cancellation
A simple example which you can see it live.
HTML:
<button @click="send">Send</button>
<button :disabled="!request" @click="cancel">Cancel</button>
JS
import axios from "axios";
export default {
data: () => ({
requests: [],
request: null
}),
methods: {
send() {
if (this.request) this.cancel();
this.makeRequest();
},
cancel() {
this.request.cancel();
this.clearOldRequest("Cancelled");
},
makeRequest() {
const axiosSource = axios.CancelToken.source();
this.request = { cancel: axiosSource.cancel, msg: "Loading..." };
axios
.get(API_URL, { cancelToken: axiosSource.token })
.then(() => {
this.clearOldRequest("Success");
})
.catch(this.logResponseErrors);
},
logResponseErrors(err) {
if (axios.isCancel(err)) {
console.log("Request cancelled");
}
},
clearOldRequest(msg) {
this.request.msg = msg;
this.requests.push(this.request);
this.request = null;
}
}
};
In this example the current request canceled when a new one starts.
The server answers after 5 seconds if a new request fired before the old one is canceled. The cancelSource
specifies a cancel token that can be used to cancel the request. For more informations check the axios documentation.
new Vue({
el: "#app",
data: {
searchItems: null,
searchText: "some value",
cancelSource: null,
infoText: null
},
methods: {
search() {
if (this.searchText.length < 3)
{
return;
}
this.searchItems = null;
this.infoText = 'please wait 5 seconds to load data';
this.cancelSearch();
this.cancelSource = axios.CancelToken.source();
axios.get('https://httpbin.org/delay/5?search=' + this.searchText, {
cancelToken: this.cancelSource.token }).then((response) => {
if (response) {
this.searchItems = response.data;
this.infoText = null;
this.cancelSource = null;
}
});
},
cancelSearch () {
if (this.cancelSource) {
this.cancelSource.cancel('Start new search, stop active search');
console.log('cancel request done');
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input v-model="searchText" type="text" />
<button @click="search">Search</button>{{infoText}}
<pre>
{{searchItems}}
</pre>
</div>
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