Why doesn’t total price calculation work when changing item quantity in React shopping cart?

  javascript, reactjs

I’m having trouble summing up the combined cost of items in my React shopping cart. I’ve used the reduce method, but in my current code when you add items to cart and redirect to checkout, total comes up as NaN unless I mess around with the quantities, and even then it’s buggy. Would appreciate any help.

Checkout.js:

import React, { useContext, useEffect, useState } from "react";
import { Context } from "../../Context";
import CartItem from "../Cart/CartItem";

function Checkout() {
  const { cartItems } = useContext(Context);

  let total = cartItems.reduce((sum, { qty, price }) => sum + price * qty, 0); //calculate total

  const numberOfItems = cartItems.length === 1 ? `1 item` : `${cartItems.length} items`;

  return (
    <div>
      {cartItems.map(item => (
        <CartItem cartItems={cartItems} item={item} key={item.id} />
      ))}
      <p>
        {cartItems.length === 0
          ? "Cart is Empty."
          : `You have ${numberOfItems} in your cart.`}
      </p>
      <h1>Total: ${total}</h1> //appears as NaN on render
    </div>
  );
}

export default Checkout;

Example product object:

    {
      id: 1,
      url: "https://picsum.photos/id/30/200/300",
      itemName: "Mug",
      itemDescription: "Lorem ipsum dolor sit amet",
      price: 5,
    }

CartItem.js

import React, { useContext } from "react";
import "./cart.css";
import { Context } from "../../Context";

function CartItem({ item }) {
  const { increaseQty } = useContext(Context);

  item.qty = 1; //assign quantity key to product object

  const options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  const dropDown = options.map(x => {
    return <option key={x}>{x}</option>;
  });

  return (
    <div className="cart-item-container">
      <img src={item.url} className="cart-img" />
      <span>
        {item.itemName}-{item.price}$
      </span>
      <select onChange={e => increaseQty(item, e.target.value)}>
        {dropDown}
      </select>
    </div>
  );
}

export default CartItem;

The bug appears when I change the quantity of multiple items in the cart, it’s throwing something off.

  function increaseQty(product, amount){
    cartItems.find(item => item.itemName === product.itemName).qty = amount;
    setQty(amount);
  };

Source: Ask Javascript Questions

LEAVE A COMMENT