Reputation: 35
I have this code:
class Cart {
private currentCart: item[];
constructor(private pService: ProductService) {
this.currentCart = [];
}
add(product) {
if (this.currentCart.find((i) => i.product === product) != undefined) {
this.currentCart[
this.currentCart.findIndex((i) => i.product === product)
].increaseAmount();
} else {
this.currentCart.push(new item(product));
}
}
}
class Item {
product: any;
amount: number;
constructor(product) {
this.product = product;
this.amount = 1;
}
increaseAmount() {
this.amount++;
}
decreaseAmount() {
this.amount--;
}
}
My problem is the first time I activated the add function, it works, it creates a new item, the second time, if I send a product that is the same one I sent from before, it should not be undefined cause it does exist, but it doesn't enter the if statement, it goes straight to the else and makes a new item, which has the same product.
Upvotes: 0
Views: 54
Reputation: 416
I think you want to check your product equality by a unique identifier, not the product itself.
The problem with checking objects in JavaScript is:
console.log({} === {}); // false
That's right. An object does not equal an object, unless it is the exact same object. Looking at your code, it seems as though your product object should be the same, since the objects are passed around by reference, but maybe something is going on under the hood of the TypeScript class constructor that causes the objects to not be the same. Or maybe somewhere else in your code is causing them to not be. At any rate, it's best to just check your product by its unique id, like so (simplified code):
add(product) {
if(this.currentCart.find(item => item.product.id === product.id)) {
this.currentCart[this.currentCart.findIndex(item => item.product.id === product.id)].increaseAmount();
} else {
this.currentCart.push(new item(product))
}
}
If you don't have unique IDs on your products, you definitely should consider adding some.
Upvotes: 1