What I am trying to do is copying a object to two states using spread operator but when I am changing one of them, other on is also changing.
Actually I am implementing an edit operation for this itemDetails, which is fetched when mounted and have multiple items inside an array. editItemIndex is passed when edit modal for that item is open. After edit item is replaced.
I am trying to copy a duplicate of itemDetails for reset as oItemDetails but the items of oItemDetails are also changed after edit.
please provide me some suggestions for avoiding copy by reference
state: {
itemDetails: [],
oItemDetails: [],
editItem: [],
editItemIndex: null,
},
actions: {
async showItemsEditModal ({state, commit}, value) {
commit('setItemsModalStatus', true);
state.oItemDetails = await {...value};
state.itemDetails = await {...value};
},
async openEditItemModal ({state, commit}, data) {
state.editItem = await {...data.data}
state.editItemIndex = await data.item_index
},
async editItem ({state, commit}, data) {
state.itemDetails.items[state.editItemIndex] = await data
},
async resetItem ({state}) {
console.log(state.itemDetails, state.oItemDetails)
state.itemDetails = await {...state.oItemDetails}
}
}
You need deep clone to avoid copy reference of deep object, use lodash clone deep or JSON.parse(JSON.stringify(value)) instead {...value}.
Note that the performance of JSON.parse and JSON.stringify isn't good, lodash clone deep is a better solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With