Mirza Irtiza
Mirza Irtiza

Reputation: 174

how to calculate all addToCart product total price in react redux

<div className='container py-4 my-5'>
  {item.length === 0 ? (
    <p>
      cart is empty, <NavLink to='/'>continoue shopping</NavLink>
    </p>
  ) : (
    item.map((cart) => {
      return (
        <div className='row py-5 border-bottom'>
          <>
            <div className='col-md-4'>
              <img
                src={cart.image}
                alt=''
                style={{ width: '100%', height: '300px', objectFit: 'contain' }}
              />
            </div>
            <div className='col-md-4'>
              <h3> {cart.title} </h3>
              <p className='lead'> {cart.description} </p>
              <p>Quantity: {cart.qty}</p>
              <strong className='lead fw-bold'>
                {' '}
                price: {cart.price * cart.qty}{' '}
              </strong>

              <div className='mt-4'>
                <button
                  className='btn btn-outline-dark me-4'
                  onClick={() => Decrement(cart)}
                >
                  <i className='fa fa-minus'></i>
                </button>
                <button
                  className='btn btn-outline-dark'
                  onClick={() => addIncrement(cart)}
                >
                  <i className='fa fa-plus'></i>
                </button>
              </div>
            </div>
          </>
        </div>
      );
    })
  )}

  <div className='checkout'>
    <h2 className='my-4'>total price: </h2>
    <button className='btn btn-outline-dark px-5 py-2 green'>Checkout</button>
  </div>
</div>;

I'm showing products in cart component using simple react, im just confused how to calculate total price of all cart product. its an react redux based application, I'm getting data from "useSelector in cart component through map function. is there any possibility to just calculate total price of all cart which i just add."

Upvotes: 1

Views: 305

Answers (1)

lpizzinidev
lpizzinidev

Reputation: 13289

You can use the reduce function to calculate the total price:

const [total, setTotal] = useState(0.0);

useEffect(() => {
    // Update total when item qty changes
    const newTotal = item.reduce((a,b) => (a.qty * a.price) + (b.qty * b.price));
    setTotal(newTotal)
}, [item]) 

...

<div className='checkout'>
    <h2 className='my-4'>total price: {total}</h2>
    <button className='btn btn-outline-dark px-5 py-2 green'>Checkout</button>
</div>

Upvotes: 1

Related Questions