Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancelling previous API requests with Axios

I am trying to follow Axios documentation to cancel repeated requests to an URL but while I get no errors the requests aren't being cancelled. I still can do as many as I want through the following method.

import axios from 'axios'

getData({commit,state,dispatch}, id){
      const CancelToken = axios.CancelToken;
      const source = CancelToken.source();
      axios
      .get("http://15.100.100.100:9999/getData/" + id,{
        cancelToken: source.token
      }).catch(function (thrown) {
        if (axios.isCancel(thrown)) {
          console.log('Request canceled', thrown.message);
        } else {
          console.log("cancel error")
        }
      })
    },

I followed Axios documentation found here https://github.com/axios/axios#cancellation

EDIT: Kaushik Makwana's answer was correct but in my case, instead of saving in a regular variable, i saved it in a state since my axios calls are made in my store.js file.

like image 812
Otorrinolaringologista -man Avatar asked Aug 06 '19 19:08

Otorrinolaringologista -man


People also ask

How do I cancel Axios requests?

You can also cancel a request using a CancelToken. The axios cancel token API is based on the withdrawn cancelable promises proposal. You can create a cancel token using the CancelToken.

How do I cancel API request?

Cancel Fetch request If you want to cancel a Fetch request, you need to use the AbortController API. You can use the constructor to create a new AbortController object. It has a read-only property AbortController.


1 Answers

you can set a global variable to store past request.

 var source;
    getData({commit,state,dispatch}, id){

              if(source){
                 source.cancel();
              }
              const CancelToken = axios.CancelToken;
              source = CancelToken.source();
              axios
              .get("http://15.100.100.100:9999/getData/" + id,{
                cancelToken: source.token
              }).catch(function (thrown) {
                if (axios.isCancel(thrown)) {
                  console.log('Request canceled', thrown.message);
                } else {
                  console.log("cancel error")
                }
              })
            },
like image 90
Kaushik Makwana Avatar answered Nov 10 '22 13:11

Kaushik Makwana