[Vuejs]-How to push an object into an array in vue

0๐Ÿ‘

So I have set the mutation getClientEngagements to use this now

getClientEngagements(state, engagement) {
      state.clientengagements.push(engagement)
    },

But by changing the mutation to this it has placed the already existing objects into a deeper nested array. see below

enter image description here

So the response.data for the new engagement only sends back from the backend that newly added engagement on the addEngagement action. is this a problem?

0๐Ÿ‘

.then(response => {
    ...// data transaction 
    context.commit('getClientEngagements', response.data)
})

Maybe you can do with the response data at first and then store it after that.

If the response data is an object, and you only want to store the value,
you can do something similar to this:

for( p in object ){
    context.commit('getClientEngagements', object[p])
}

If the response data is an array, then you can try to use for to get the value you want and then push in the state.
You should do the transaction of data according to your needs at first for your case.

0๐Ÿ‘

Thanks for all the help, but I actually ended up needing to add a extra mutation and use that as the commit, because I am defining to seperate lists of engagements. One for the client and one for all clients. here is the new mutation

addClientEngagement(state, engagement) {
      state.clientengagements.push(engagement)
    },

which I then use in my action here

addEngagement(context, engagement) {
      axios.post(('/engagements'), {
        client_id: engagement.client_id,
        return_type: engagement.return_type,
        year: engagement.year,
        assigned_to: engagement.assigned_to,
        status: engagement.status,
        done: false
      })
      .then(response => {
        context.commit('addClientEngagement', response.data)
      })
      .catch(error => {
        console.log(error)
      })
    },

and then this mutation happens

getClientEngagements(state, clientengagements) {
      state.clientengagements = clientengagements
    },

Previously it was using this mutation to add the engagement to the array which was why it was replacing the array with the new object. see below for old mutation

addEngagement(state, engagement) {
      state.engagements.push ({
        id: engagement.id,
        client_id: engagement.client_id,
        return_type: engagement.return_type,
        year: engagement.year,
        assigned_to: engagement.assigned_to,
        status: engagement.status,
        done: false
      })
    },

Hopefully I am making sense in my explanation

Leave a comment