Unleashing the power of Vuex with promise chaining

One challenge I am facing is making API calls to retrieve an array of endpoints, which are then used to fetch data from another API.

// Raise isLoading flag
    this.$store.commit('isLoading', true);
    
    // Initial data fetch
    this.$store.dispatch('getAvailableProductGroups').then(() => {
      // Call API for every available product
      for(let group of this.$store.state.availableProductGroups) {
        // Check if it's the last API call
        this.$store.dispatch('getProductsData', group).then((response) => {
          // Reset isLoading flag
          // this.$store.commit('isLoading', false);
        });
      }
    }); 
  

When fetching the endpoints list from the first API, I set up an isLoading flag. However, I am unsure how to determine when the last promise has been resolved in order to reset the flag.

Answer №1

// Set isLoadign flag to true
this.$store.commit('isLoading', true);
// Fetch initial data
this.$store.dispatch('getAvailableProductGroups')
  .then(() => {
    // Call API for each available product group
    return Promise.all(this.$store.state.availableProductGroups.map(group => {
      // Check if it's the last API call
      return this.$store.dispatch('getProductsData', group);
    });
  })
  .then((allResults) => {
    this.$store.commit('isLoading', false);
  });

However, it MUST be implemented in the store actions, not in the vue-component.

Answer №2

If you want to handle multiple promises in an array, you can use .map() and then resolve them all at once with .all()

Approach without async/await

this.$store.commit('isLoading', true);
this.$store.dispatch('getAvailableProductGroups').then(() => {
    // Create an array of promises
    const groupPromises = this.$store.state.availableProductGroups.map(group =>  this.$store.dispatch('getProductsData', group))
    Promise.all(groupPromises).then( values => {
        // Results of all promises
        console.log(values);
        this.$store.commit('isLoading', false);
    });
});

Using async/await

async function performTasks() {
    try {
        this.$store.commit('isLoading', true);
        await this.$store.dispatch('getAvailableProductGroups')
        // Create promises array
        const groupPromises = this.$store.state.availableProductGroups.map(group =>  this.$store.dispatch('getProductsData', group))
        // Wait for all promises to resolve
        const arrayOfValues = await Promise.all(groupPromises);
        this.$store.commit('isLoading', false);
    } catch(err) {
        console.log(err);
    }
}

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

Error code 405 (METHOD NOT ALLOWED) is received when attempting to make a post request to an API

Struggling to develop a basic front end that can communicate with my API. The API functions properly as I am able to retrieve and send data using the POSTMAN client. Fetching data from the server and displaying it on the frontend works fine, but encounteri ...

Efficiently submitting multiple forms in a single click

On my photo portfolio admin page, I have created a feature to caption, keyword, and credit each photo. Previously, I had multiple forms listed dynamically with submit buttons for each form. With over 20 photos/forms on the page, this process became tedious ...

Sequelize - issue with foreign key in create include results in null value

When using the create include method, the foreign key is returning null, while the rest of the data is successfully saved from the passed object. This is my transaction model setup: module.exports = (sequelize, DataTypes) => { const Transaction = ...

Leveraging image values for selecting an image from a collection and showcasing it (Javascript)

I have a collection of images that I want to enlarge upon clicking. Here is what I currently have: <div class="gallery"> <div> <img src="content/imggallery/img1.jpg" class="oldimg" value="0"> </div> ...

Patience is key when awaiting a state update in the Vue.js router's beforeEnter guard

My goal is to control access to specific pages in my vue router. Instead of embedding authentication logic in each component, I would prefer to have a 'hasUserAccess' check in my child-routes only where it's necessary. { path: 'admi ...

VueJS is unable to access the requested resource due to the absence of an 'Access-Control-Allow-Origin' header

Currently, I am working on a VueJS application that requires calling an external API. The code snippet below demonstrates my approach: this.$http.get(myAPIurl) .then(response => { return response.json(); ...

What steps do I need to take for webpack to locate angular modules?

I'm currently in the process of setting up a basic application using Angular 1 alongside Typescript 2 and Webpack. Everything runs smoothly until I attempt to incorporate an external module, such as angular-ui-router. An error consistently arises ind ...

Can Angular Universal SSR be activated specifically for Googlebot User Agents?

I am aiming to activate Angular Universal SSR only when the User Agent is identified as Googlebot. However, I am uncertain about how to instruct Angular Universal SSR to deliver server side rendered HTML exclusively if the User Agent is Googlebot. server ...

Exploring a JavaScript object to verify if a property contains nested data elements

I am currently working on traversing through the object above in order to determine if a contact is a member of a specific list. For instance, if the user is a member of the list with an ID of 2022, I want to display their first name (which is also includ ...

My component fails to load using Angular Router even though the URL is correct

I have been experiencing an issue while trying to load my Angular component using the router. The component never appears on the screen and there are no error messages displayed. app-routing-module { path: '', redirectTo: '/home', ...

React Error: Unable to iterate over this.state.descriptions

Currently facing an issue while trying to resolve this error https://i.stack.imgur.com/BZ304.png The goal is to generate an automated form using the following function: let descriptionsForm = ( <form> {this.state.descriptions.map((d ...

Issue with ngTable: Error retrieving data for server-side pagination

I am currently working on setting up a server-side table using ng-table. However, I am encountering some issues with the getData function. It keeps giving me errors such as $defer.resolve is not a function or params is not defined. I noticed that I can ac ...

Updating Kendo by modifying the Angular model

While working on a project with Angular, I recently discovered the Kendo-Angular project available at . I successfully integrated Angular-Kendo into my project and it seems to be functioning well, except for updating models in the way I am accustomed to. ...

Gridsome fails to update data following adjustments in API

Currently, I am retrieving data from a Strapi API as a Collection. It is working fine, but whenever I make changes in Strapi, the data does not update in Gridsome. The only way to get the new information is by restarting the Gridsome server. I am running ...

Tips for implementing JWT in a Node.js-based proxy server:

I am a Node.js beginner with a newbie question. I'm not sure if this is the right place to ask, but I need ideas from this community. Here's what I'm trying to do: Server Configurations: Node.js - 4.0.0 Hapi.js - 10.0.0 Redis Scenario: ...

Modify the universal variable through a jQuery action

As a newcomer to jQuery with limited experience in JavaScript, I find myself facing a dilemma. I am working on a jQuery range slider that displays two year values, and I have successfully stored both the minimum and maximum years in a variable. However, I ...

Ensure you are focusing on elements exclusively contained within the parent table and not any child tables nested within its cells

Looking for some help with a unique situation here. I'm struggling to find the right selector for this task. For reference, you can check out the jsfiddle at this link: http://jsfiddle.net/NZf6r/1/ The scenario is that I have a parent table containin ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

Chorme is throwing a CSRF token mismatch error when working with Laravel API Sanctum

Having an issue with my Vue app and backend Laravel setup. I am using SPA Authentication for authentication. Everything works fine in localhost, but when I deployed it to the server, there are some issues. After sending a login request to sanctum/csrf-co ...

Issues have been identified with the functionality of the Am charts v3 XY in conjunction with a

I'm currently working on a project with angularJS and utilizing the npm package amcharts3 "^3.21.15". I've encountered a minor issue regarding the logarithmic scale in my XY chart. Below is my chart without the logarithmic scale: View working ch ...