Process the API response before moving on to the next mutation

Upon the creation of my Vue app, the requestUserProfile action is triggered. The main goal is to fetch data from the "/api/user/" API call and store it in the state before executing the setUserProfile mutation.

The issue arises when the setUserProfile mutation is being called even before the data has been set in the state after receiving the API response. Is there a way to ensure that the requestUserInfo function is fully executed before triggering the setUserProfile?

Below is the code snippet I am currently working on:

state() {
    return {
        requestUser: null,
        profile: null
    }
},
mutations: {
    setUserInfo (state) {
        apiService("/api/user/")
        .then(data => {
            state.requestUser = data["username"]
        })
    },
    setUserProfile (state) {
        let endpoint = "api/profile/";

        if (state.requestUser) {
            apiService(endpoint)
            .then(data => {
                state.profile = data
            })
        }
    }
},
actions: {
    async requestUserInfo ({ commit }) {
        commit('setUserInfo')
    },
    async requestUserProfile ({ dispatch, commit }) {
        await dispatch('requestUserInfo') // wait for `requestUserInfo` to finish
        commit('setUserProfile')
    }
},

Answer №1

It appears there may have been some confusion regarding the usage of mutations and actions. Mutations are meant to be synchronous and should only be used to modify state directly. On the other hand, actions can be asynchronous, allowing them to make requests for data and then use mutations to update the state with that data.

To implement this in your code, make sure it follows this structure:

mutations: {
  setUserData (state, data) {
    state.userData = data
  },
  setUserDetails (state, details) {
    state.details = details
  }
...
actions: {
  async fetchData ({ commit }) {
     const response = await fetchService("/api/data/")
     commit('setUserData', response)
  },
  async fetchUserDetails ({ dispatch, commit, state }) {
      await dispatch('fetchData') // wait for `fetchData` to finish
      let endpoint = "api/details/";
      if (state.userData) {
        const details = await fetchService(endpoint)
        commit('setUserDetails', details)
      }
  }

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

Verification of email address is required, emails must be unique and not duplicated

I am working on validating email addresses to ensure they are not repeated. So far, I have successfully pushed them from the server into an array using regex for validation. What steps should I take next to compare and further validate these emails? ...

Incorporate Vue into a portion of your current jQuery project

I am facing an issue with my old project where I am trying to use Vue to show or hide certain fields in a form. I have imported Vue from CDN and initialized a new Vue app. Initially, I tried setting an id to the body of the project, but it did not work as ...

Switching the checkbox value upon clicking a div element

One challenge I am facing is with a checkbox that saves its value and title in the local storage when clicked. This checkbox is located within a div, and I want the checkbox value to change whenever any part of the div is clicked. Despite my efforts, I hav ...

Condense a lineup of names into only two rows

I have a challenge where I need to showcase a list of names separated by commas, pulled from an array in my React component. The HTML output should appear as follows: <div> <span>Liza</span>, <span>Eric</span>, <span>Mic ...

Disabling Camera Dampening in a 3D Environment Upon Click

I am currently working on a project that involves implementing a damping effect for the camera when the user stops rotating it using their mouse. While this effect is important, I also want to provide users with the option to disable the damping effect by ...

Renaming ngModel in an AngularJS directive's "require" attribute can be achieved by specifying a different alias

I need help with a basic AngularJS directive: <my-directive ng-model="name"></my-directive> I want to change the "ng-model" attribute to "model", but I'm unsure how to pass it to the "require" option in the directive. Here is the full co ...

AngularJS: Implement ng-repeat directive to generate two separate HTML containers

I have a collection of items and I want to divide them into two separate containers. Is there a way to achieve this using ng-repeat? <div> <ul> <li>Some item</li> <li>Some item</li> <li&g ...

JavaScript: Reversing the Sequence of XML Elements

I am looking to reverse the order of this list using JavaScript. I have tried different methods that I know, but the below code shows it in a straight manner. I am not familiar with XML nodes and how to completely reverse it. <messages> <mess ...

Function will not work if the element is not present on the page initially

I came across a scenario where I have this function: $(function(){ $(".todo-task").click(function(){ $(".todo-task").css('background-color','green'); }); }); The issue arises because the "todo-task" element is not init ...

Combining text in Nativescript with the help of Label

I am trying to combine a string in a Label. The desired result is : USD 3000, where 3000 is the price number retrieved from the database. I have tried using the following code: <Label row="2" col="1" text="USD {{ price }}" /> However, it does not w ...

Exchange the positions of two divs that have the same class

Can someone help me with a small part of my project that I'm stuck on? I need to fadeIn/fadeOut between two divs with the same class, but I want to keep the function as short as possible. My current solution only works if both divs are hidden at the ...

Is it possible to add an element to an array field in a document using Mongoose/Node?

Currently, I'm working with a Mongoose schema that includes an array field designed to hold multiple strings: const exampleSchema = new.mongooseSchema({ field1: String, field2: String, field3: [String] }) My goal is to configure the ...

Nested variable declarations within block scoping can result in various types of errors

I'm currently exploring the concept of block scoping in ES6 and encountered an interesting issue that I need help understanding: In my initial test, I attempted the following code snippet and observed the error mentioned within the comments: { c ...

Utilizing onClick with material-ui button - functioning flawlessly for a single interaction

I have been attempting to encapsulate a Material-UI button within another component. Everything seems to be working well, except for when I try to handle the onClick event - it appears to only work once. Here is an example that demonstrates the issue: ht ...

A guide on utilizing Higher Order Components (HOC) to assign a specific value to a component within a React

Currently, I am working on creating a Higher Order Component (HOC) in React.js that assigns values to the "color" parameter in an icon component. I have three different colors available, each with its corresponding value: Primary: #f7a014 Secondary: ...

BlueMist Failure Predicted After Following Error

Looking for insights on why NodeJS instances crash during a Next tick or Mongoose pre error. How can we improve application stability as we troubleshoot these errors? Will IBM be introducing more resilience measures? One idea could be to set up a Linux do ...

Obtain the value for every span class and insert the corresponding string into the input field

I have a series of tags labeled as 'tag-label' in spans. My goal is to combine the values of these tags and insert them into an input field, separating each value with commas. To demonstrate this, I've created a JSFiddle that showcases the ...

What is the most effective method for implementing the lightweight-charts package in a Nuxt project?

I am looking to integrate the lightweight-charts package into my Nuxt project. Despite searching, I couldn't find any examples specifically for Nuxt projects. I have managed to implement it using some methods, but I'm not sure if I'm followi ...

Tips for displaying a refresh indicator while making an ajax call for refreshing data:

I have successfully implemented jQuery code that refreshes a specific div every 10 seconds without reloading the entire page. However, during this refresh process, the user does not visually perceive any changes happening in the browser. While there are n ...

Is AJAX.call functioning properly in every browser except for Firefox?

I encountered an issue with an ajax load in Firefox. Every time I try to load, I keep receiving a message that says 'unreachable code after return statement'. Despite my efforts to find a solution, I have not been successful in resolving it. Inte ...