I am currently working on a basic shopping cart application and I am facing an issue when users add multiple quantities of the same product. The total is not being calculated correctly.
Here is my current logic:
Data structure for Products,
product = {
'productName': 'Sample Product',
'productImage': productImage,
'rate': 100,
'quantity': 1
}
this.addToCartService.cartItems.subscribe(product => {
if (product) {
const productExistInCart = this.cartItems.find(({ productName }) => productName === product.productName);
if (!productExistInCart) {
this.cartItems.push(product);
return;
} else {
productExistInCart.quantity++
}
this.totalPrice = this.cartItems
.map(item => item.rate)
.reduce((prev, curr) => prev + curr, 0);
}
});
HTML Structure
<div class="cart_box dropdown-menu dropdown-menu-right show">
<ul class="cart_list" *ngIf="cartItems.length">
<li *ngFor="let cartItem of cartItems; let i = index">
<a (click)="removeFromCart(i)" class="item_remove"><i class="ion-close"></i></a>
<a href="#"><img src="{{cartItem.productImage}}" alt="cart_thumb1">{{cartItem.productName}}</a>
<span class="cart_quantity"> {{cartItem.quantity}} x <span class="cart_amount"> <span
class="price_symbole">₹</span>{{cartItem.rate}}</span></span>
</li>
</ul>
<div class="cart_footer">
<p class="cart_total">Total: <span class="cart_amount"> <span
class="price_symbole">₹</span>{{totalPrice}}</span>
</p>
<p class="cart_buttons"><a href="cart.html" class="btn btn-default btn-radius view-cart">View Cart</a><a
href="checkout.html" class="btn btn-dark btn-radius checkout">Checkout</a></p>
</div>
</div>
I'm currently stuck and unsure how to update the total of existing items in the cart. Any help would be appreciated.
Current Output Shown Below
https://i.sstatic.net/luVDF.png
In the image above, the total should be 400 but it is displaying as 100. There seems to be an issue with the calculation.