[Vuejs]-Cancel a previous axios request on new request in Vue Js

0๐Ÿ‘

โœ…

I have referred the documentation and other sources for this question, and i found a solution which suited me best.


this.cancelFunc();
//Below line creates a cancel token for this request 
let axiosSource = axios.CancelToken.source();

this.request = { cancel: axiosSource.cancel };

//then we pass the token to the request we want to cancel.
axios.get('/Url/GetUser/'+ this.forms.username, {cancelToken: axiosSource.token,}).then((response) => {
    if (response.data.error) {
        this.errorNya = response.data;
        this.loading2 = false;
    } else {
        this.errorNya.username = "";
        this.options = response.data;
        this.loading2 = false;
        this.disableButton = true;
    }
},
    cancelFunc() {
        if (this.request) 
        this.request.cancel();
      },

i know this will not be the best way to do this, but this solved my problem.

Leave a comment