Axios cancel token preemptively cancelling request before it is initiated

Currently, I am working on implementing cancellation of axios calls in my project. After reviewing the axios documentation, it appears to be quite straightforward, which can be found here.

To begin, I have defined some variables at the top of my Vue component:

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

Of course, I have also included import axios from 'axios'; at the top.

Next, I have a method for fetching the API data. Within this method, I want to be able to cancel any ongoing requests, especially if a user is filtering multiple times in quick succession.

async fetchPartners(inputToClear) {
            source.cancel();
            ...

            try {
                const response = await axios.get(`../partners?limit=1000${this.createRequestString()}`, {
                    cancelToken: source.token
                });
                // I have included the cancelToken in the request

                this.partners = response.data.data;
            } catch (error) {
                if (axios.isCancel(error)) {
                    console.log('Request canceled', error.message);
                }
                const fetchErrors = this.utilGlobalHandleErrorMessages(error);

                this.utilGlobalDisplayMessage(fetchErrors.message, { type: 'error' });

                return [];
            } finally {
                ...
            }
        },

Despite following the code example provided in the axios documentation, I am encountering an issue where the call is being cancelled before even making the request. The console displays:

Request canceled undefined

It appears as though the call is being cancelled before it is even initiated, despite calling source.cancel() before the request. Any insights on this issue would be greatly appreciated.

Answer №1

It is recommended to use throttling for your requests rather than canceling them.

If throttling is not suitable for your needs, you can try the following approach:

const CancelToken = axios.CancelToken;
let source;

async fetchPartners(inputToClear) {
    if(source){
      source.cancel();
    }
    ...
    source = CancelToken.source();

    try {
      const response = await axios.get(`../partners?limit=1000${this.createRequestString()}`, {
       cancelToken: source.token
      });
      // The cancelToken has been added to the request here

      this.partners = response.data.data;
    } catch (error) {
      if (axios.isCancel(error)) {
        console.log('Request canceled', error.message);
      }
      const fetchErrors = this.utilGlobalHandleErrorMessages(error);

      this.utilGlobalDisplayMessage(fetchErrors.message, {
        type: 'error'
      });

      return [];
    } finally {
      ...
    }
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing Public Photos from Facebook Users

Is it possible to create a web app that can retrieve all public photos from any user's Facebook account using their profile URL? For instance, some Facebook profiles allow non-logged in users to view profile pictures and cover photos. I am developing ...

Mocha test failing to trigger function execution

I've been developing an Express.js application that includes a feature for creating appointments with a post request. This feature involves retrieving and saving data from a third-party API, followed by sending updated API data in the subsequent reque ...

Customizing Tooltip Labels in Highcharts-VueUsing a Custom Label Formatter Function for Tooltips

I've been struggling to implement my custom function for formatting x and y axis values in a tooltip within a Highcharts vue component. Here's the code snippet I'm working with: data() { return { currencySymbol: "$", }; }, ...

AngularJS: Users must click submit button twice for it to function properly

It's puzzling that I have to click the submit button on my form twice before it triggers the save function below. My HTML is written in Pug format. Below is a snippet of my HTML template: <form ng-submit="save()"> <div class="form-group" ...

Execute function upon initial user interaction (click for desktop users / tap for mobile users) with the Document Object Model (DOM)

Looking to trigger a function only on the initial interaction with the DOM. Are there any vanilla JavaScript options available? I've brainstormed this approach. Is it on track? window.addEventListener("click", function onFirstTouch() { console.l ...

A guide to displaying the contents of a component that includes another component using slot rendering

In the code snippet below, you can see that the component ButtonDigitizePolygon.vue includes a button with a named slot. The component NDVIComparisonGui.vue is responsible for rendering ButtonDigitizePolygon.vue. My goal is to have App.vue render both NDV ...

Creating a canvas texture on tube geometry with three.js for optimal display on iPad devices

I have a 3D model of a tube geometry with 18000 coordinates on the production side. To simplify, I am selecting every 9th coordinate to plot 9000 coordinates for building the tube geometry using only the CanvasRenderer. When utilizing vertexColors: THREE. ...

Exploring the principles of object-oriented design within the context of Node

I am facing challenges with the asynchronous flow of Node.js. Let's assume we have the following class: function myClass() { var property = 'something'; var hasConnected = false; this.connect = function(params) { // Logic to conn ...

When you click on Highcharts, a bigger graph will be displayed

I am working on a feature that allows users to zoom in on small charts on my website. This involves revealing an overlay div and displaying a larger chart with the same data as the clicked chart inside it. function DrawSmallChart() { chart_data = [1, 2, 3 ...

Converting an array of object keys into integers only can be done using JavaScript

Here is an array of objects with various nutrients and their values: [ {nutrient: "Energy", per100: "449kcal", per35: "157kcal", id: 6} {nutrient: "Fat", per100: "24.4g", per35: "8.6g", id: 1} {nutrient: "Saturated fat", per100: "4.5g", per35: "1.6g ...

Enable a VueJS directive on-the-fly from a separate directive

My goal is to simplify the process of binding a form control to vuejs by creating a directive that handles all necessary events for tracking changes in a form field. Rather than manually adding multiple event listeners like this: <input type="text" na ...

Having trouble toggling the dropdown submenu feature in a Vuejs application?

.dropdown-submenu { position: relative; } .dropdown-submenu .dropdown-menu { top: 0; left: 100%; margin-top: -1px; } <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Tutorial ...

Dealing with 404 errors encountered when making requests to external websites, utilizing either basic Javascript or JQuery

I have links in my application that redirect to external websites. For example, a link might look like this: <http://www.google.com'>>General Search<>. Users input the href and we dynamically create the link without any validation of it ...

What is the process for making an XHR request to a server located remotely

Do you think the code below is sufficient for XHRing a remote server? I tried putting the full server URL in the open method of the XHR object, but it didn't work. I'm not sure if something else needs to be added. <script type="text/javascrip ...

How to Hide Validation Messages Automatically Using Knockout on Page Load

I have been facing a persistent issue where error messages are displaying onload and I want them to appear only on save. Although I have been successful in many cases and can adjust my code accordingly, this particular bug seems to be causing continuous pr ...

Updating by clicking with auto-prediction feature

I have implemented an autosuggestion feature to display results from a database table while typing in an HTML field, and I am looking to utilize JavaScript to post another value from the same row where the autosuggested values are stored. https://i.stack. ...

Exploring Data Objects in Vue.js

I have a data() object in my Maincomponent.vue. Inside the data(), there is an array named myDatabase that contains multiple objects. My goal is to utilize methods to access the fields within myDatabase. I am looking to create functionality to toggle the ...

Is it possible to efficiently bring in NPM packages with their dependencies intact in Deno?

I stumbled upon a helpful post outlining how to incorporate NPM modules in Deno: How to use npm module in DENO? The catch is, the libraries used in the example have absolutely no dependencies. But what if I want to utilize a dependency like Axios (not th ...

Ensuring secure Firebase JSON database access through Firebase authentication

I am currently developing a mobile app using Ionic 3 with Angular, and I am utilizing the Facebook Native Cordova plugin for user login. In terms of Firebase database security, the documentation provides guidance on rules syntax like this: { "rules" ...

The way in which notifications for updates are displayed on the Stack Overflow website

Could someone shed some light on how the real-time update messages on this platform are created? For instance, when I am composing a response to a question and a new answer is added, I receive a notification message at the top of the page. How is this fun ...