Home » vue » Updating existing data object using vuex store

Updating existing data object using vuex store

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have search google and went to every possible Q&A and I couldn’t figure out what to do.

I have a vueX store action that updating user data from one component(that works fine!)

But, I want to update the same user data object by adding another key & value to the object and not overwrite the current state.

Mutations:

const mutations = {
    updateUser(state, user) {
        console.log("Mutation User:", user);
        state.userToSave = user
    }
}

Actions:

const actions = {
    updateCurrentUser({ commit }, user) {
        commit('updateUser', user)
        console.log("User: \n", user)
    },

First time I called the dispatch to update user data object from a signup form(work fine! I get all the data I need):

submitForm(){
  this.$store.dispatch({
    type: "updateCurrentUser",
    user: this.userObject
  })

Second time I called the dispatch in order to add specific key to the object:(overwriting the exist data and replace it only with this.designID value

afterPick(){
  this.closeModalDesign = false;
  this.$store.dispatch({
    type: "updateCurrentUser",
    user: this.designID
  })
  this.paymentInit = true;
},

Any suggestions? I would like to receive a short explanation also, it will help me to better understand all the vuex thing

Answers:

It looks like you’re updating the whole user object instead of just overwriting the user’s "designID". To overwrite only the user’s designID you would need to create a new vuex mutation:

updateUserDesignID: (state, designID) => {
  state.user.designID = designID
}

then call from your component:

this.$store.dispatch({
  type: "updateUserDesignID",
  designID: this.designID
})