You need to double click to successfully update the array in Vue/Vuex

Recently, I delved into Vue/Vuex and find myself at a loss with my current code. The method I trigger on click is as follows:

Export (item) {
  this.exportObj = {
    start: this.dates[0],
    end: this.dates[1],
    userid: item.id,
  };

  this.getAllByFilter(this.exportObj);

  if (this.dateRangeText == "No dates seleceted") {
    this.disValue = true;
  } else {
    this.disValue = false;
  }

  if (this.exportData.events.length > 0) {
    this.exportData.events = [];
    console.log("Emptyed array because there was already data there!");
  } else {
    console.log("Well this was empty already :O");
  }

  for (let i = 0; i < this.allEvents.length; i++) { 
      var timeStart = new Date(this.allEvents[i].start).getHours(); 
      var timeEnd = new Date(this.allEvents[i].end).getHours();
      var hourDiff = timeEnd - timeStart;

      this.exportData.events[i] = {
        start: this.allEvents[i].start,
        end: this.allEvents[i].end,
        title: this.allEvents[i].title,
        userid: this.allEvents[i].userId,
        hours: hourDiff,
      };
  }

  this.exportData.title = "Report for " + item.firstName + " " + item.lastName + " for dates in range " + this.dateRangeText;
  this.exportData.fileName = item.firstName + " " + item.lastName + " - " + this.dateRangeText;
  this.exportData.worksheetName = item.firstName + " " + item.lastName + " " + this.dateRangeText;
},

Despite having fulfilled the promise just once, the array I'm pushing data to (exportData.events) remains empty until I hit the button twice. I utilize a getter for allEvents, and the promise resolution shows that it's successful. As indicated below, the promise resolves on the first click, but the data within the loop fails to populate the empty array. Any insights or suggestions would be greatly appreciated.

https://i.sstatic.net/duJHb.png

Store:

const state = {
    events: []
};

    const actions = {
        getAllByFilter({ commit }, exportObj) {
        calendarService.getAllByFilter(exportObj)
            .then(
                events => commit('getAllSuccess', events),
                error => commit('getAllFailure', error)
            );
        },
    };
    
    const getters = {
    allEvents: state => state.events
    };
    
    const mutations = {
    getAllSuccess(state, events) {
        state.events = events;
        },
    };
    
    export const calendar = {
        namespaced: true,
        state,
        actions,
        mutations,
        getters
    };

Answer №1

The issue lies here:

this.getAllByFilter(this.exportObj);

The Promise generated by this action was not properly handled. Make sure to return your Promise and then await its completion.

const actions = {
    getAllByFilter({ commit }, exportObj) {
    return calendarService.getAllByFilter(exportObj)
        .then(
            events => commit('getAllSuccess', events),
            error => commit('getAllFailure', error)
        );
    },
};

Update your Export method like so:

async Export (item) {
  this.exportObj = {
    start: this.dates[0],
    end: this.dates[1],
    userid: item.id,
  };

  await this.getAllByFilter(this.exportObj);
  ....

To provide a better user experience, consider displaying a progress bar, loading dialog, or disabling the button until the Export process is complete.

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

JavaScript menu that pops up

Hello everyone, I've recently created an HTML5 file that, when clicked on a specific href link, is supposed to display an image in a smooth and elegant manner. However, so far it hasn't been working for me as expected. Instead of smoothly popping ...

Which method is more effective: utilizing AJAX to retrieve page elements, or just toggling their visibility?

When it comes to web development, particularly in jQuery, should I preload my page and use jQuery to manipulate the DOM, or should I do it the other way around? This debate involves: <div id="item1" ></div> <div id="item2"></div> ...

Having trouble getting `sudo apt install npm` to work? You might be encountering the error message "The following packages have unmet dependencies

Creating dependency tree Retrieving status information... Completed Certain packages could not be installed. This might indicate that you have requested an unrealistic scenario or if you are utilizing the unstable version, some necessary packages could s ...

What is the best way to show two icons next to each other within a React component?

For my school project, I am working on developing an app and encountering a challenge. I have been trying to display two icons side by side on a screen using React (I've been learning React for 5 months but still consider myself a beginner). However, ...

What is the best way to define a constant in the main scope that relies on a function parameter?

I'm currently exploring next-auth and I'm interested in leveraging unstable_getserversession. According to the documentation, I need to import options from another file. import { authOptions } from 'pages/api/auth/[...nextauth]' Howeve ...

Tips for dynamically loading fresh Google Adsense code with JavaScript without any user interaction

Recently, Google made a change in their ad code by replacing <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js</script> with <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygo ...

Displaying Images on top of Images with React/Javascript/NextJS

I have two images. Let's say image 1 is a thumbnail for news content. I would like to overlay a promotional PNG banner on top of this image and create a new output image. This output image will be used as the OG (Open Graph) image. How can I achieve t ...

Analyzing registration details stored in an array against user login credentials

With two buttons available - one for sign up and the other for log in, my goal is to gather input form values from the sign-up section into an array. Following this, I aim to compare the user input from the sign-up with that of the log-in, informing the us ...

Utilizing d3.json: changing the URL with dynamic data

Just getting started with d3 and building a sankey diagram. I came across a sample that uses an external .json file with d3.v3, even though it is an outdated version. Since my tree also relies on this version, I'd like to stick to just one d3 version. ...

Deciphering the intricacies of VUEX-STORE modules

Consider this scenario: I have two separate lists - one for income and one for outcome. Each list has its own storage, and I am adding these storages as modules in index.js. While I could create a single repository for both income and outcome, displaying ...

Sometimes, the `undefined` TypeError can unexpectedly pop up while making Ajax calls

Here is my issue with AJAX request and response: I have around 85 HTML pages that all use the same AJAX request. However, when working with these files, I sometimes encounter the following error. AJAX $(document).ready(function(){ localStorage.setIte ...

Neither the view nor the controller are being properly loaded into the index.html file

I initially had my angular app loading my javascript correctly, but the routing was not properly set up. I am currently trying to resolve this issue, but now my javascript alert is not even popping up, indicating that the file is not connected. Can anyone ...

How can the ordering of dynamically generated components be synchronized with the order of other components?

Currently, I'm delving into Vue 3 and encountering a specific issue. The tabs library I'm using only provides tab headers without content panels. To work around this limitation, I've come up with the following solution: <myTabs/><!- ...

Modifying CSS property values by handling a returned validation error

Allow me to describe a scenario I've created. Please excuse any language errors in my explanation. I have designed a form for users to submit values. Within this form, users can choose an option - one of which is "Others specify...". When this option ...

Immerse yourself in a world of virtual reality with the cutting-edge VR Vide

Currently, I am in the process of developing a virtual panoramic tour that features various panoramas linked together with hotspots. Each panorama contains a video hotspot that plays a video. However, I have encountered an issue where every time a new sce ...

What is the best way to retrieve the value of this event in a React component?

Is there a way to retrieve the value of an input field? Typically, I would use event.target.value to do so. However, in this case, that method is not viable because the path of event.target leads me to an li element instead: https://i.sstatic.net/0iB9v.pn ...

I attempted to upload an image using the Google Drive API, but encountered an error in the response

I am attempting to upload an image using the Google Drive API, but I encountered an error in the response message. The error reads as follows: "Failed to load resource: the server responded with a status of 403 ()" ...

A guide to displaying a PDF preview using React Dropzone

I am struggling to find a way to display previews of PDF files that I'm uploading using react-dropzone. Although PNG and JPG files are working correctly, I would like to be able to show the user either the actual PDF or an image representation of it. ...

Tips for saving user input from an HTML form into a database using PHP, and then transferring it to a variable in JavaScript

I've been working on a Wordpress project that involves two separate pages. The first page has a form for users to submit their name, which is then stored in a custom table in the database. After submitting the form, the user is redirected to another p ...

Encountering a JavaScript issue where the error "function is undefined" appears when attempting to import the GL

I'm a beginner in Javascript and I'm currently working on a project that involves displaying a 3D model in a modal. Everything was running smoothly until I attempted to include an import statement. Once I added the line import {GLTFLoader} from & ...