Why isn't the VueJS component loading state getting updated after Canceling an Axios network request?

Within my dashboard, there is a dropdown for filtering dates. Each time a user changes the dropdown value, multiple network requests are sent using Axios.

To prevent additional API calls when the user rapidly changes the date filters, I utilize AbortController in JavaScript to cancel any previous pending requests.

On my VueJS component, I employ custom loading states to display loading screens based on request statuses as shown below:

Vue HTML template

      <template>
        <div v-if="loadingSpendingCard">
          Loading...
        </div>

        <SpendingCard v-else/>
      </template>

Vue Methods

{
...,
methods: {
  fetchData(){
      this.$store.dispatch("CANCEL_PENDING_REQUESTS");

      this.loadingSpendingCard = true;
       axiosApiClient.get("/user-spending");
        .then((response) => {
          console.log(response)
        })
        .catch((error) => {
          console.log(error);
        })
        .finally(() => {
          this.loadingSpendingCard = false;
        });
 }
}

Using Axios request interceptors, I add an AbortController to each request and manage their states from Vuex for future cancellation. To cancel these requests, I use Vuex actions that are triggered at the start of fetchData() following this guide here.

The issue arises when the loadingSpendingCard state remains false even after aborting requests and sending new ones. It should update to true for each new request.

fetchData() gets called every time the date filter value changes, leading to successful completion of previous requests and initiation of new ones.

I attempted keeping the state as true and not changing it if error === "canceled", which worked temporarily. However, with over 20 requests, this solution does not suffice.

  fetchData(){
      this.$store.dispatch("CANCEL_PENDING_REQUESTS");
      
      this.loadingSpendingCard = true;
       axiosApiClient.get("/user-spending");
        .then((response) => {
          console.log(response)
        })
        .catch((error) => {

         if(error === "canceled"){
          console.log("Canceled request")
         }else{
          this.loadingSpendingCard = false;
          console.log(error);
          }

        })
 }

Why is the loadingSpendingCard state not updating to true?

Answer №1

At times, the usage of 'this' inside axios may not work properly. To avoid this issue, it is recommended to define 'self' at the beginning of your function.

var self = this

Then, you can use 'self' like this:

          self.loadingSpendingCard = false;

Here is an example of how to incorporate this into your code:

fetchData(){
  var self = this
  this.$store.dispatch("CANCEL_PENDING_REQUESTS");

  this.loadingSpendingCard = true;
   axiosApiClient.get("/user-spending")
    .then((response) => {
      console.log(response)
    })
    .catch((error) => {

     if(error === "canceled"){
      console.log("Canceled request")
     }else{
      self.loadingSpendingCard = false;
      console.log(error);
      }

    })

}

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

Is there a method in VBA to access elements generated by javascript code?

After spending several hours conducting thorough research on Google (including browsing StackOverflow), I've been trying to find a method that would allow me to target HTML elements generated by JavaScript in VBA. For instance, using ie.Document.getE ...

Postpone the processing of a message in the Service Bus Queue until a specific time using NodeJS

Despite trying multiple tutorials, I have been unable to achieve the desired result so far. Currently, my setup involves a nodejs app that sends messages to the Service Bus Queue and another nodejs app that continuously polls it. The goal is to schedule a ...

Vue JS i18next: Handling Single Translation String Fallbacks

Recently, I've been utilizing i18next, and I decided to set a fallback value for some translated strings in case they are not available in the selected language. Here's an example: en: base.json "yes": "yes" "no": "no" fr: base.json ...

Creating an interface that accurately infers the correct type based on the context

I have an example below of what I aim to achieve. My goal is to start with an empty list of DbTransactInput and then add objects to the array. I experimented with mapped types to ensure that the "Items" in the "Put" property infer the correct data type, w ...

Execute an executable file with elevated permissions using Node.js

I'm looking to run an .exe file as an administrator using Node. I attempted the following code, but it's not working: exec('runas /user:Administrator "app.exe"', function(err, data) { console.log(err) ...

Ways to show a corresponding number beneath every image that is generated dynamically

I have a requirement to show a specific image multiple times based on user input. I have achieved this functionality successfully. However, I now need to display a number below each image. For example, if the user enters '4', there should be 4 im ...

The store for WrappedApp was just initialized using withRedux(MyApp) { initialState: undefined, initialStateFromGSPorGSSR: undefined }

I am trying to create multiple routes with express and next.js. After running npm run export, I encountered the following message: next export info - using build directory: C:_PROJECT.next info - Copying "static build" directory info - Launching 3 wor ...

Enhance User Experience with ngDialog Modal's Multi-pane Feature for Angular

Looking at the ngDialog example, they showcase a modal with multiple 'panes' that can be scrolled through: . After going through the ngDialog guide, I couldn't find a straightforward way to achieve this. Any suggestions on how to add a butt ...

Preventing page reload in Supabase with NextJS when the website loses focus and regains it

I am working with the structure in _app.js of my Next.js app. // _app.js // import ... import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs' import { SessionContextProvider } from '@supabase/auth-helpers-react' // ...

Form data sent using Axios POST request does not contain any information on the server side

The code snippet above shows the client-side implementation. It confirms that the data is not empty and the file is being uploaded successfully. export function addGame(data) { return dispatch => { const formData = new FormData(); formData. ...

What is the maximum file size that the data link is able to store?

For instance, a file like an image, video, or sound can be saved in the data link Take an image for example, it may be stored with the initial link: data:image/jpeg;base64,/..... followed by various characters. But, is there a specified size limit at whic ...

What causes offsetHeight to be less than clientHeight?

INFORMATION: clientHeight: Retrieves the height of an element, taking into account padding offsetHeight: Obtains the height of an element, considering padding, border, and scrollbar Analyzing the Data: The value returned by offsetHeight is expected to ...

Issue with host header detected in MERN stack configuration

"proxy": "https://mango-artist-rmdnr.pwskills.app:5000", While attempting to establish a connection between my frontend and backend, I encountered an issue with an invalid host header. The backend is operating on port 5000, and the fr ...

Issue with accessing VueJS Global Mixin readonly variable in component method

Trying to integrate vuejs as a frontend framework with WP restapi, I faced the challenge of needing the wordpress generated api url accessible to all vue components. Here is my approach: Vue.mixin({ data: function () { return { get apiUrl () { ...

Continuous polling with Ajax in Rails does not trigger the display of an alert box

Trying to implement ajax polling using the RailsCast tutorial on ajax polling (#229) but encountering an issue where the alert box doesn't pop up after running the server. Here's the code in app/views/quotes/index.js.erb: alert('Hey') ...

How to switch around div elements using CSS

There are two unordered list items in a container div and one swap button. When the swap button is clicked, the order of items needs to change. This functionality can be achieved using the following swap function. var ints = [ "1", "2", "3", "4" ], ...

Embracing the node mindset with a Java foundation

As a Java Developer, I have become accustomed to working in a sequential manner where tasks are executed one after the other or concurrently with multiple threads. The organization of code in a sequential way seemed logical under this paradigm. However, wh ...

Empty array is logged by the server after sending a JavaScript variable through post request

When I use console.log(request.body), the terminal displays {} instead of logging the variable ownerSteamId. Here is my code: Server-side JavaScript: const express = require('express'); const app = express(); const bodyParser = require('bod ...

Firebase will automatically log users out after one hour of inactivity

After conducting thorough research, I have learned that Firebase updates a refresh token every hour because Firebase ID tokens expire after one hour. It is mentioned that the automatic refreshing of tokens by Firebase occurs without any action required fro ...

What sort of JavaScript WYSIWYG text editor provides formula support?

Looking for a Javascript rich text editor that offers formula selection in the toolbar. Any recommendations? ...