3
votes

I have a parent component with a grid of rows and I am using vuex to pass data, as i add a new record I would want to open the newly added record in a modal window. I am emitting an event and opening the modal with the first record (index = 0). The problem is that, as it is an ajax call to add record using an vuex "action", the emit happens before the record is added. How can I wait till the record is added with event? or Is there a better way to do it?

Below is the code:

<!-- Grid Component -->
<grid>
   <addrow @newrecordadded="openNewlyAddedRecord"></addrow>
   <gridrow v-for="row in rows" :key="row._id"></gridrow>
</grid>

computed: {
    rows(){
       return this.$store.state.rows;
    }  
},
methods:{
    openNewlyAddedRecord(){
        this.openmodal(this.rows[0])
    }
}

my store.js

state: {
    rows : []
}

so in addrow component once the user clicks on submit form it dispatches to vuex

methods:{
    onsubmit(){
        this.$store.dispatch('addrow',this.newrow);
        this.$emit("newrecordadded");    
    }
}

actions.js

addrow({ commit,state }, payload){
    var url = "/add";
    Axios.post(url,payload)
    .then(function(response){
        commit('addnewrow',response.data);
    });
}

mutations.js

addnewrow(state,payload){
    state.rows.unshift(payload);
}

Or alternatively can we pass a call back function to dispatch?

1

1 Answers

6
votes

You can make the addrow action return a promise, like so:

addrow({ commit,state }, payload){
  var url = "/add";
  return Axios.post(url,payload)
    .then(function(response){
      commit('addnewrow',response.data);
    });
}

In the onsubmit method in your component you can now do:

this.$store.dispatch('addrow',this.newrow).then(() => this.$emit("newrecordadded");)