I am trying get the total items in cart. The problem is though that it only gets the total amount of items that are unique items in the cart. If an item is duplicated e.g. has 2 items of the same it does not add to Total Items
Here is a CodeSandBox example:
Any help here would be appreciated!
CodePudding user response:
You are displaying cart.items.length
as the "Total Items" but that's just the number of individual items without taking the quantity
into account. Instead you can use this:
<span>{cart.items.reduce((accum,item) => accum item.quantity, 0)}</span>
The reduce
function will run through the array of items
and total up all of the quantity
values. See the documentation here.
This is just a short way to do this:
let totalItems = 0;
for (const item of cart.items) {
totalItems = item.quantity;
}
console.log("Total Items: " totalItems);