First, the Function Executes Prior to the Store Action in Vue

Within my brands.js store, there is an action that invokes the API:

  getBrandMerchants({ commit }, id) {
    commit('setLoading', true);
    BrandService.getBrandMerchants(id)
      .then((response) => {
        commit('setBrand', formatter.deserialize(response.data.result.brand));
        commit('setMerchants', formatter.deserialize(response.data.result.merchants));
        commit('setLoading', false);
        console.log('First');
      })
      .catch((error) => {
        if (error.response.status === 401) {
          dispatch('alert/error', error.response, { root: true });
        } else {
          Toast.open({
            type: 'is-danger', message: error.response.data.meta.message,
          });
        }
      });
  },

The components in use contain the following code snippets:

...mapState('brands', ['merchants']),
...mapActions('brands', ['getBrandMerchants']),

Upon trying to execute this method within a component:

    addMerchantsToBrandGroup(index) {
      const { id } = this.rows[index].brand;
      if (id === null) { return; }

      this.getBrandMerchants(id)
        .then(() => {
          console.log('Second');
          this.rows[index].merchants = this.merchants
        });
    },

The output in the console appears as:

Second
First

I am seeking a way to ensure the console displays:

First
Second

Answer №1

According to @deceze:

The inclusion of async and await in the following functions was crucial for resolving the issue:

  async getBrandMerchants({ commit }, id) {
    commit('setLoading', true);
    await BrandService.getBrandMerchants(id)
      .then((response) => {
        commit('setBrand', formatter.deserialize(response.data.result.brand));
        commit('setMerchants', formatter.deserialize(response.data.result.merchants));
        commit('setLoading', false);
        console.log('First');
      })
      .catch((error) => {
        if (error.response.status === 401) {
          dispatch('alert/error', error.response, { root: true });
        } else {
          Toast.open({
            type: 'is-danger', message: error.response.data.meta.message,
          });
        }
      });
  },

This addition in conjunction with:

async addMerchantsToBrandGroup(index) {
      const { id } = this.rows[index].brand;
      if (id === null) { return; }

      await this.getBrandMerchants(id)
      console.log('Second');
      this.rows[index].merchants = this.merchants
    },

resulted in successful problem resolution. Many thanks!

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

Unexpected '->' found on page during loading

After migrating my WordPress site from localhost to the live server, I encountered an issue where "-->" appeared before the page finished loading. Can anyone explain this strange behavior? In addition to this issue, the jQuery scripts I had implemented ...

A secure method for dynamically adding a JavaScript file

In my lang folder, I store language variables for a website. To dynamically include the desired file based on the user's language selection, I use session variables. For example, if the user selects English, 'en' is stored in the lang variab ...

How is it possible for the zero value to still be submitted even after I have included display error messages?

I have written some code to display error messages in PHP, but it seems that the error message is not displayed when all fields are empty. This results in submitting empty values to the database. <!DOCTYPE HTML> <html> <head> <style ...

Expand the data retrieved from the database in node.js to include additional fields, not just the id

When creating a login using the code provided, only the user's ID is returned. The challenge now is how to retrieve another field from the database. I specifically require the "header" field from the database. Within the onSubmit function of the for ...

Using Node JS as both an HTTP server and a TCP socket client simultaneously

Currently, I am developing a Node.js application to act as an HTTP server communicating with a TCP socket server. The code snippet for this setup is displayed below: var http = require('http'); var net = require('net'); var url = requi ...

Adding and removing classes in NativeScript: A step-by-step guide

Attempting to lower the opacity of my StackLayout while making an Ajax API call. The structure of my page is as follows: <Page loaded="pageLoaded" class="page" xmlns="http://www.nativescript.org/tns.xsd"> <ActionBar title="Settings" clas ...

Using dynamic values in Angular functions

Here is the code snippet I am working with: $scope.testByValue = function() { $scope.fChanged($scope.lists.title); }; But I am facing an issue on the page where the value for: $scope.testValue = testValue; The variable testValue is being assigned a ...

Tips for passing state values into getServerSideProps to fetch data from an API

At the moment, I am dealing with a situation where I have a context containing the state of a name. My current task is to extract this state so that I can utilize it in an API call which relies on it. age.js import { useStateContext } from "@/context ...

I am interested in extracting specific data from the JSON response

I am trying to extract the value of the message parameter under the messages array where the parameter name is equal to documentId (highlighted in bold below). However, the code I have tried so far does not achieve this as needed. dynamic obj = JsonConver ...

Using Jquery to load a css background image with a loader

I am seeking suggestions on how to display a loader between button clicks while waiting for a background image to fully load. Thank you <html > <head> <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script type= ...

Storing the model on the server with the help of Backbone and NodeJS

As a beginner in Backbone and AJAX, as well as being new to Node.js which my server is built on, I am working on saving a model using the Save method in Backbone for a webchat project for university. Right now, my goal is to send the username and password ...

Remove all images within the HTML using jQuery

I have dynamically generated a div using the code snippet below: typebox.innerHTML += "<div id='idtypebox' class='typebox'><img id='typeImg' width='30px' height='30px' src="+d[o].src+"></div ...

Vue.js not accepting an object as input value

I am working with an input type text in my vue js application. This is the initial code snippet: <input type="text" v-model="answer[index]" > Here is the updated code: <table> <tr v-for="(question_overall, index) in questions"> ...

The power of Karma, AngularJS, Bootstrap, and the window variable working

As I work on testing my application, I am facing an issue with loading files using Karma into PhantomJS. The problem arises when one of the files triggers a page reload due to window variables. The files are being included in this manner: files: [ &a ...

Here's a method for transferring data from one array to another: when there is existing data in the

Although this may seem simple to some, I have been struggling with it for hours without any success. If I have the following data in an array: var tDataValues = { id: "TenantID", text: "FullName", username: "Username", cnic: 'CNIC&ap ...

I'm encountering a type error stating that children are not defined when attempting to establish parent-child relationships from a flat array. What

Trying to establish a parent-child relationship between modules based on their IDs. Ran into an issue with the function I used, as it returned an error stating that children were not defined. const data = [ { module_id: "96ac027b-b5ce-4326-b5db- ...

Ways to obtain distinct JavaScript key codes for [ and { and ' and "

Greetings all! I'm currently working on a text editor that has the ability to automatically complete brackets and quotes by using jQuery. In order to achieve this, I am utilizing key codes. However, I have encountered an issue where the characters [ a ...

Executing Javascript with Ajax requested data - A guide to making your script run smoothly

Battlefield Page In the graphic provided, there is a battlefield page featuring 20 users. To capture and store this data in a MySQL database, I have created a JavaScript script. However, an issue arises when trying to collect data from the next page after ...

Transforming Jquery into vanilla JavaScript and sending a POST request

Hey everyone, I'm in the process of converting Jquery code to pure javascript and encountering some difficulties with the following snippet: $.post('ajax_data',{action:'service_price',service:service,quantity:quantity,dripfeed:drip ...

Creating a Checkerboard Plane using Three.js

I am currently working on a Three.js project for a webpage 3D example where I want to create a checkerboard. The issue I am facing is that my code assigns three colors, but I only need two colors (black and white). How can I adjust the mathematical calcu ...