Search code examples
vue.jsvuexvuex-modules

Vuex unexpectedly updates 2 state objects


I've got a list of companies. When the user clicks on a list item, this company is set as "selectedCompany" in the store and the single item view is displayed. To allow the user to edit different sections, he can switch to edit mode. When this happens, the selectedCompany is copied to another state variable: "companyToUpdate"

My intended behaviour is for the user to edit the cloned version so that in case he cancels, the cloned version is destroyed and the underlying actual version is not touched. If he proceeds to send the edit to the server, the response will replace the current "selectedCompany".

The problem I am having is that whenever I change the cloned version, the original version changes as well when its not supposed to.

Here's my code, but maybe there's also an altogether better way to do this...

vuex store module:

const state = {
    selectedCompany: {},  
    companyToUpdate: false,
    editMode: false,
}

const actions = {

setEditMode: ({ commit, dispatch }, payload) => {  
        dispatch('singleCompany/cloneSelectedCompany', payload, { root: true } )
        commit('setEditMode', payload); 
    },


cloneSelectedCompany: ({ commit, state }, payload) => {
        if (payload) { let clone = state.selectedCompany; commit('cloneSelectedCompany', clone);  }
        if (!payload) {  commit('cloneSelectedCompany', payload);   }
    },

updateCompanyLocally: ({ commit }, payload) => { commit('updateCompanyLocally', payload); },
}

const mutations = {
 setEditMode: (state,payload) => { state.editMode = payload },

cloneSelectedCompany: (state,payload) => { state.companyToUpdate = payload },

updateCompanyLocally: (state,payload) => { 
        state.companyToUpdate[payload.fieldName] = payload.input
     },
}

None of my mutations update the selectedCompany state, and yet it does change. PS I am also using vuex-persistedstate...maybe that messes with it in some way


Solution

  • The issue originates from JS itself, as objects are passed by reference, not by value, so Vuex will point to the same object in memory.

    To create a new object based on the existing object, you can use a hacky parse and stringify inside your cloneSelectedCompany mutation:

    let clone = state.selectedCompany;

    should be

    let clone = JSON.parse(JSON.stringify(state.selectedCompany));

    Depending on your use case it could also possible that you need to deep clone your object.