Cancel previous request using axios with vue.js
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>
2022 UPDATE
To cancel requests use AbortController
const controller = new AbortController();
const signal = controller.signal
axios.get('/foo/bar', { signal })
.then(function(response) {
//...
});
// cancel the request
controller.abort()
Explanation: We first create a controller with AbortController and grab the reference to its associated AbortSignal object by accessing AbortController.signal
property.
Then to associate the signal with the request, we pass that signal as an option inside the request's options object. Then to cancel/abort the request we call controller.abort()
.
The amazing thing about this is that we can use it in the exact same way with the fetch API:
const controller = new AbortController();
const signal = controller.signal
fetch('/foo/bar', { signal })
.then(function(response) {
//...
});
// cancel the request
controller.abort()
Cancel token has been deprecated since v0.22.0 and shouldn't be used in new projects.
2020 UPDATE: How to cancel an axios request
generate a cancelToken
and store it
import axios from 'axios'
const request = axios.CancelToken.source();
pass the cancelToken
to the axios request
axios.get('API_URL', { cancelToken: request.token })
Access the request you stored and call the .cancel()
method to cancel it
request.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;
}
}
};