'The latest object does not compute the latest object added

I'm working on a simple add-to-cart function using React.js, The pushing of the product object works, but the computation of total seems incorrect. The main problem is it does not compute the latest object added.

addProduct = () =>{
    const totalPrice = this.state.shoppingCart.reduce((acc, product) => acc + product.price, 0);
    this.setState({
      shoppingCart: this.state.shoppingCart.concat({ name: 'Milk', price: 100 }),
      total: totalPrice,
    }); 

  };


Solution 1:[1]

I don't see you adding the latest added product's price to the totalPrice.

I think this function looks better:

    addProduct = (product) =>{
    const newCart = [...this.state.shoppingCart,product]
    const totalPrice = newCart.reduce((acc, product) => acc + product.price, 0);
    this.setState({
      shoppingCart: newCart,
    }); 
    this.setState({total : totalPrice});
  };

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 Erfan