Summing numbers return Not a Number in React

I am adding total for each product in the cart page. I have quantity and price in each object which I multiply to get total value for the product, but since user can have multiple products I have to sum total’s of all objects in the cart. The problem I have is that summing total’s return Not a Number. I am not sure why I get this, because if I log total of each object I get type of number.

const productsObj = [{
    id: 1,
    name: 'Sweater',
    size: 'M',
    gender: 'Men',
    price: 2300,
    printPrice: 180,
    minQuantity: 1,
    total: 2300,
  },
  {
    id: 2,
    name: 'Shirt',
    size: 'M',
    materijal: 'Pamuk',
    gender: 'Men',
    price: 1500,
    printPrice: 180,
    minQuantity: 1,
    total: 1500,
  }],

const [products, setProducts] = useState(productsObj);

//onChange on quantity input:
onChange={(event) => {
                               setProducts(
                                  products.map((item) => {
                                    if (item.id === e.id) {
                                      return {
                                        ...item,
                                        quantity: event.target.value,
                                        total: e.price* event.target.value,
                                      };
                                    } else {
                                      return item;
                                    }
                                  })
                                );
                              }}

//function that sums all the total's
  const allTotal = () => {
    let sum;

    products.forEach((e) => {
      sum += e.total;
    });

    return sum; //NaN
  };

>Solution :

Try adding an initial value;

let sum = 0;

Leave a Reply