Search code examples
javascriptreactjsredux

Calculate Total Price in React-Redux


I have a "Cart" component that displays the title, code, quantity, price of products! I would like if someone could help calculate "price total" when I send various products into the cart! My "Cart" component code (bare in mind that {cartProduct.price} is the price of one product but when I add more than one of this product to cart it updates the quantity, but not the Total Price)

class Cart extends Component {
   removeFromCart = (product) => {
    const cartProducts = this.props.cart 
    const updatedCartProducts = cartProducts.filter(item => item.id !== product.id);
  
  }

  render () {
    const cartProducts = this.props.cart
    return (
      <>
        <PanelHeader size="sm" />
        <div className="content">
          <Row>
            <Col xs={12}>
              <Card>
                <CardHeader>
                  <CardTitle tag="h4">Products List</CardTitle>
                </CardHeader>
                <CardBody>
                <table class="table table-striped table-hover">
                  <thead>
                    <tr>
                      <th scope="col"><strong>#</strong></th>
                      <th scope="col"><strong>Name</strong></th>
                      <th scope="col"><strong>Code Item</strong></th>
                      <th scope="col"><strong>Quantity</strong></th>
                      <th scope="col"><strong>Price Total</strong></th>
                    </tr>
                  </thead>
                    <tbody>
                      {cartProducts.map((cartProduct, index) => (             
                      <tr key={cartProduct.id}>
                    <th scope="row">{index +1}</th>
                    <td>{cartProduct.title}</td>
                    <td>{cartProduct.code}</td>
                    <td>{cartProduct.quantity}</td>
                    <td>{cartProduct.price}</td>
                    <td><button onClick ={() => this.props.removeCart(cartProduct)} className="btn btn-danger cart-button px-4">Remove</button></td>
                      </tr>))}
                    </tbody>
                </table>
              </CardBody>
            </Card>
          </Col>
        </Row>
      </div>
    </>
    )
  }
}


const mapStateToProps = (state)=> {
  return {
      cart: state.cart
       }
  }

const mapDispatchToProps = (dispatch) => { 
      return {
        removeCart: (product) => {dispatch(removeCart(product))}
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Cart);

and my reducer file where I update the items quantity (I m not sure if its needed) is the following:

import { ADD_TO_CART } from './constants'
import { REMOVE_FROM_CART } from './constants'
// import { ADD_QUANTITY} from './constants'
// import { SUB_QUANTITY}  from './constants'
// import { EMPTY_CART}  from './constants'


const initialState = {
    cart: [],
  }
const ShoppinReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_TO_CART:

      let newCart = [...state.cart]
      let itemIndex = state.cart.findIndex(obj => obj.id === action.payload.id)
      let currItem = state.cart[itemIndex]

      if (currItem) {
      currItem.quantity = parseInt(currItem.quantity) + 1
      state.cart[itemIndex] = currItem
      newCart = [...state.cart]

      }

      else {

      newCart = newCart.concat(action.payload)
      }

      return {
      cart: newCart
      }

    case REMOVE_FROM_CART:
      const cart = [...state.cart]
      const updatedCart = cart.filter(item => item.id !== action.payload.id)

      return {
        ...state,
        cart: updatedCart
      }
    
    default:
    return state
  }
}
  export default ShoppinReducer

I have an idea that I must create a function that will multiply quantity*price but not sure how to implement it! Thank you in advance!


Solution

  • I wouldn't handle this will Redux, It would be better to calculate the values of the cartItems on your React component/page.

    You can calculate the total price by looping through the cart, getting the price of each product and adding in each price to a single variable.

    {cartItems.reduce((acc, item) => acc + item.quantity * item.price, 0).toFixed(2)}
    
    • toFixed() rounds the total price to 2 decimal places

    This way you would not have to update the Redux store every time the user add/removes/updates the quantity of an item.