Home > database >  React get total amount items in cart
React get total amount items in cart

Time:10-29

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: enter image description here

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);
  • Related