Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel previous request using axios with vue.js

I am using axios and vue.js.I have google it,and check the axios docs but still cannot understand how to do it.

like image 573
Ready Dev Avatar asked May 24 '18 19:05

Ready Dev


2 Answers

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;
    }
  }
};
like image 108
Roland Avatar answered Sep 21 '22 21:09

Roland


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>
like image 25
live2 Avatar answered Sep 23 '22 21:09

live2