24

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

4 Answers 4

44

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;
    }
  }
};
Sign up to request clarification or add additional context in comments.

5 Comments

Unless I'm missing something here, this example actually still tries to cancel a request even if it was completed. The answer below by @live2 makes sure the cancelToken is reset to null after a successful request
Robin Hoodie this cancels the previous request but not if it was completed. Did you checked out the codesandbox example ?
In the codesandbox you've provided (which contains excellent code), you're right, you can't click the cance button if the request was completed. I meant the example in the answer itself, there you can still call cancel even if the request was cancelled because the cancel variable is never set to null on completion of the request.
@Robin-Hoodie I updated my answer + the tiny app + a simple live example. I hope it's more clear now.
2022: CancelToken is deprecated. AbortController should be used now in new projects
16

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>

Comments

1

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;

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.