Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Try adding an initial value;

let sum = 0;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading