I am seriously having a mental breakdown over this right now...
I am working on a small vue based website. In this particular Section I want to add an Item to a List.
Here is my Code:
addItem() {
this.items.push(this.itemToBeProcessed);
this.itemToBeProcessed.id = null;
this.itemToBeProcessed.name = "";
this.itemToBeProcessed.price = null;
this.itemToBeProcessed.buyers = [];
this.itemToBeProcessed.amountPurchased = null;
},
async checkInput() {
let item = this.itemToBeProcessed;
if (item.name != "" &&
item.id != null &&
item.price != null &&
item.amountPurchased != null &&
item.buyers != []) {
console.log(this.itemToBeProcessed.id)
console.log(this.itemToBeProcessed)
console.log(this.itemToBeProcessed.id)
this.addItem();
} else {
alert("Not all Fields are set correctly!")
}
}
My Data Structure:
data() {
return {
itemToBeProcessed: {
id: null,
name: "",
price: null,
amountPurchased: null,
buyers: [],
},
items: [],
}
}
As you can see, I tried console logging my itemToBeProcessed. In the checkInput method I have three console logs. My problem is now that the console writes the correct id every time. The Item I want to log on the other hand is only correctly logged if I either comment out the resets in addItem() or if I completly comment out the method call. Otherwise all attributes are null, or [].
I have literally no idea how this would be my mistake at all.
Thank you for a response!
CodePudding user response:
When you add your item with items.push
, you don't push a copy in your list, you push a reference to the same object as this.itemToBeProcessed
.
So, when you reset all fields on this.itemToBeProcessed
right after the push, then you're also resetting the fields of the element in the list, since it refers to the same object!
A possible solution could be to use a shallow copy:
this.items.push(Object.assign({}, this.itemToBeProcessed));
Here you push a new object that has all the fields copied from this.itemToBeProcessed
, this should solve your issue
Below find an example to put into light the underlying issue:
// With an element as a simple type like string, no issue here.
// I'll change element after being pushed, the list stays "the same".
let list = [];
let element = "aaa";
list.push(element);
console.log(list);
element = "bbb";
console.log(list);
element = null;
console.log(list);
// But if we're dealing with objects, changing element would "change the content" of the list as well.
// Objects variables hold _references_ to an object, they internally refer to the same one!
list = [];
element = { name: "aaa" };
list.push(element);
console.log(list);
element.name = "bbb";
console.log(list);
element.name = null;
console.log(list);