How can you make a button in Vue only visible after all API calls have successfully retrieved the data?

Is there a way to make the report button visible only after all the data has been loaded from the latest click of the budget button? Currently, when the budget button is clicked, it retrieves budgets and displays them in a Vue grid using Kendo Grid. To speed up data loading, the grid initially loads with some data before making additional API calls for two more columns of data. These subsequent API calls are processed 10 at a time in a loop due to potential delays. What's the simplest approach to show the button once all the data has finished loading?

I've shared my current method for retrieving budgets and the computed property that determines when the report button should appear. One issue I'm encountering is that even if I reset the estimateAmounts object array at the start of the getBudgets method, existing loops may still be running from previous calls and affecting the comparison with the data object in my computation. Any suggestions on how best to address this challenge would be greatly appreciated. Feel free to reach out if you need more information.

    data() {
                return {
                    budgets: [],
                    estimateAmounts: {},
                }
           },
methods: {
    async getBudgets() {

                this.isLoading = true;
                this.budgets = []
                this.estimateAmounts = {}
                const data = await api.budget.getBudgetReport({ 
                  accountIds: this.accountIds.map(a => a.accountId),
                  salesRepIds: this.selectedSalesReps.map(sr => sr.userId),
                  startDate: this.startDate, 
                  endDate: this.endDate 
                })
                this.budgets = data.map(d => { return { ...d, startDate: new Date(d.startDate) } })
                this.isLoading = false;

                // group calculations in 10's to run concurrently and return results faster
                let idSets = chunk(data.map(d => d.budgetId), 10)
                for (const ids of idSets)
                    api.budget.calculateTotalsForBudgets(ids, this.user.userId)
                        .then(res => this.estimateAmounts = { ...this.estimateAmounts, ...res })
            },
    },

    computed: {
        setButtons() {
                        return Object.keys(this.estimateAmounts).length == this.budgets.length && this.budgets.length > 0
                    },
    }

Answer №1

If my understanding is correct, you simply wish to wait for all parallel API calls to finish before displaying a button in the template. This can be accomplished using await Promise.all without the need for any computed property. Here's an example:

this.displayButton = true;
await Promise.all(
    idSets.map(async (ids) => {
        await api.budget.calculateTotalsForBudgets(ids, this.user.userId);
    })
);
this.displayButton = false;

I introduced a new displayButton state as an illustration, but you could possibly utilize your existing isLoading state -- just place it below.

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

Creating an ngInclude directive on the fly: A step-by-step guide

Whenever I insert this into my HTML, everything functions correctly: <div ng-include="'my-template.html'"></div> However, when attempting to dynamically create that ngInclude directive using jQuery (after the DOM has loaded), it fai ...

What is the process for submitting a post request with custom fields to the Wordpress rest api?

Currently, I am attempting to make a post request to /wp-json/wp/v2/posts while also including custom fields. However, it seems that although the request field is successfully being sent, the custom fields are not updating with the data I am trying to send ...

Error message received from Express middleware: "Unable to modify headers after they have been sent."

I have created middleware for my Node Express app to perform the following tasks: Checking all incoming requests to determine if they are from a bot Allowing requests for raw resources to proceed Serving an HTML snapshot if the request is from a bot How ...

Is it mandatory to employ the spread operator in the process of updating an object while using the useState hook?

Recently delving into hooks, I stumbled upon an insightful passage in the official documentation regarding Using Multiple State Variables: It is noteworthy that updating a state variable in hooks replaces it entirely, as opposed to merging it like in th ...

Using AngularJS: Implementing ng-include with a custom function

When using ng-include, I have encountered a peculiar issue. I am attempting to retrieve the template path by invoking a function defined in the controller that returns the path based on the parameter passed. Below is my code snippet: <tr ng-repeat="det ...

What's the best method for efficiently hiding/showing a large number of DOM elements?

Imagine you have a maximum of 100 elements that remain consistent in type and format, but their content changes. These elements are connected to an input field and will update as the user types. What would be the most efficient approach for maximizing per ...

Ways to eliminate class from HTML code

Trying to detect if a navigational element has a specific class upon click. If it has the class, remove it; if not, add it. The goal is to display an active state on the dropdown button while the dropdown is open. The active state should be removed when a ...

What's the best way to trigger an event within a tag in a Vue.js component?

app.js Vue.component("popup",{ template : /*html*/` <div class="popup is-active" > <div class="popup-background"></div> <div class="popup-card"> <header class=" ...

How to declare a variable using new String() and s = '' in Typescript/Javascript

What is the correct way to declare an array of characters or a string in JavaScript? Is there a distinction between an array of characters and a string? let operators = new String(); or let operators = ''; ...

Invoking res.download() in the Express framework

It's puzzling why this issue is occurring, and it's quite frustrating. I was expecting the file to be downloaded in line with the guidelines provided in the Express documentation. Below is the code snippet I am using: //within React (App.js) ...

Having trouble with the search function in my array, as it is consistently returning false instead of the expected result

Aim: I am working on creating a basic search bar that allows users to input a zip code and matches it with zip codes stored in an array. The objective is to develop a function that can determine whether the entered zip code exists in the array or not, and ...

Encountering the error "TypeError: Unable to access property 'controls' of undefined" when utilizing formArray in Reactive forms

Hi there, I am currently working on creating a dynamic form using formArray in Angular. However, I have run into an issue with the error message "TypeError: Cannot read property 'controls' of undefined." import { Component, OnInit } from ' ...

"Process the contents of a file by reading it line by line in a

Currently, I am reviewing the documentation for the nodejs readline module in order to tackle a task that involves reading a very large file line by line. The solution using readline seems promising, although I require it to read lines synchronously - mean ...

Issue with Framer Motion Modal: Animation presence fails to function

Currently, I am facing an issue with the exit animation of a modal created using framer motion. While the initial animation on opening the modal works perfectly fine, the exit animation fails to trigger and the modal disappears abruptly without any transit ...

What are the reasons behind the significant difference in speed between using Node's Object.create(foo) and new Foo()?

For my Sudoku solver in JavaScript, I decided to take a purely functional approach by using immutable 9x9 puzzle arrays. Every time a new number is inserted, a new array is created. Implementation 1: New SudokuPuzzle In the initial version, I utilized th ...

Retrieve all records from a table using Prisma client

I need to retrieve all data from a table using Prisma. How can I achieve this? (SELECT * FROM application) const applications = prisma.application.findMany({ // Retrieves all fields for the user include: { posts: { ...

Unable to load dynamic data in Angular 2 smart table

Currently, I am utilizing Angular 6 along with smart table by visiting this link: . Everything was functioning smoothly, until the moment I attempted to switch from static to dynamic data: The following code works perfectly and displays all the content ...

What is the most effective way to send a list of objects to a Controller

https://i.stack.imgur.com/oyi5v.png This form is for billing purposes. You can add the item name, quantity, and price multiple times to calculate the total amount. Once you click on submit, all the included items along with other parameters like bill nu ...

"Encountering a hiccup with the Firebase service worker in Messaging and Firebase

I am interested in developing a small web application to explore the capabilities of Firebase Cloud Messaging for web apps. My intention is to utilize Firebase Hosting as the hosting platform for my app. ISSUE: Upon allowing the notification pop-up on my ...

Unresolved promise: Internal server issue

I encountered an exception while working on my Nativescript app. EXCEPTION: Uncaught (in promise): Server error JS: ORIGINAL STACKTRACE: JS: Error: Uncaught (in promise): Server error JS: at resolvePromise (/data/data/com.yourdomain.appname/files/app/ ...