Ready Dev
Ready Dev

Reputation: 557

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.

Upvotes: 24

Views: 41923

Answers (4)

live2
live2

Reputation: 4265

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>

Upvotes: 16

agm1984
agm1984

Reputation: 17132

Here's how I did it in a Pinia store:

import { defineStore } from 'pinia';

export const useSomeStore = defineStore('some', {
    state: () => ({
        someList: [],
        abortController: null,
    }),

    actions: {
        async getSomeList() {
            try {
                if (this.abortController) {
                    this.abortController.abort();
                }

                this.abortController = new AbortController();
                const signal = this.abortController.signal;

                axois.get('admin/providers/list', { signal })
                    .then((res) => {
                        this.someList = res.data.data;
                        this.abortController = null;
                    }).catch((err) => {
                        this.isFetching = false;
                    });
            } catch (error) {
                console.log('error', error);
                throw error;
            }
        },
    },
});

The important thing is this:

            // step 1: if abortController is active, it means a request 
            // is in progress and we need to cancel it before proceeding
            if (this.abortController) {
                this.abortController.abort();
            }

            // step 2: abortController wasnt active, so activate one
            // and grab its signal
            this.abortController = new AbortController();
            const signal = this.abortController.signal;

            // step 3: make request and pass in signal
            await axios.get('admin/providers/list', { signal });

            // step 4: unset the abortController after request is done
            this.signalController = null;

Upvotes: 1

Roland
Roland

Reputation: 27719

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;
    }
  }
};

Upvotes: 42

Abdunnasir K P
Abdunnasir K P

Reputation: 117

First define some variables

data: function () {
    return {
        request_source : ''
    }
},

Then inside the method

source = CancelToken.source();
if(this.request_source != '')
    this.request_source.cancel('Operation canceled by the user.');

this.request_source = source;

axios
   .get(
       URL,
          {
              params:{key1: value1},
              cancelToken: this.request_source.token
          }
    )

Upvotes: -1

Related Questions