'Why is my Grand Total not updating after I increase or decrease the quantity in React?

This is a basic application that I am working on using React and Bootstrap. Here, The Grand Total is not changing when I update the quantity. I have attached the Sandbox link. Please let me know the mistake.

https://codesandbox.io/s/reactbootstrap-forked-k9n86s?file=/src/App.js

  /********Total quantity *************** */
  const grandTotal = () => {
    let total = 0;
    for (let product of products) {
      total += product.price * product.quantity;
    }
    console.log(total);
    return total;
  };
<tr className="text-end">
    <td colSpan={3}>Grand Total:</td>
    <td>{grandTotal()}</td>
</tr>

Thanks.



Solution 1:[1]

In grandTotal you still refer to the initial array (products). It should be product.

  const grandTotal = () => {
    let total = 0;
    for (let p of product) {
      total += p.price * p.quantity;
    }
    console.log(total);
    return total;
  };

NOTE: Be clear when naming things. I would name initial products as initialProductsand use products variable name in useState.

Edit reactBootstrap (forked)

Solution 2:[2]

the name of your variable is the problem products

const grandTotal = () => {
    let total = 0;
    for (let prd of product) {
      total += prd.price * prd.quantity;
    }
    console.log(total);
    return total;
  };

products point to this variable

const products = [
  {
    sno: "123",
    name: "Apple Watch",
    price: 290,
    quantity: 2
  },
  {
    sno: "567",
    name: "Samgung Watch",
    price: 278,
    quantity: 5
  },
  {
    sno: "785",
    name: "Cas",
    price: 123,
    quantity: 1
  }
];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Amila Senadheera
Solution 2 Arash Ghazi