Home > OS >  The latest object does not compute the latest object added
The latest object does not compute the latest object added

Time:03-12

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,
    }); 

  };

CodePudding user response:

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});
  };
  • Related