Salman
Salman

Reputation: 1024

Redux return total price in cart

Hi my redux app currently adds cart items, but I would like to function to count the total price.

How can I do this in redux?

Currently my Reducer looks like this.

const cartItems = (state = [], action) => {
    switch (action.type)
    {
        case 'ADD_TO_CART':
        // console.log('CarItems.JS', action.payload)
            if (state.some(cartItem => cartItem.id === action.payload.id)) {
                // increase qty if item already exists in cart
                return state.map(cartItem => (cartItem.id === action.payload.id ? { ...cartItem, qty: cartItem.qty + 1 } : cartItem));
            }
            return [...state, { ...action.payload, qty: 1 }]; // else add the new item to cart

        case 'REMOVE_FROM_CART':
            return state
                .map(cartItem => (cartItem.id === action.payload.id ? { ...cartItem, qty: cartItem.qty - 1 } : cartItem))
                .filter(cartItem => cartItem.qty > 0);
    }
    return state
} 

export default cartItems 

Solution

Calculate total sum and return it.

const mapStateToProps = (state) => {
    let totalPrice = 0;
    state.map((item) => { 
      totalPrice += item.price * item.qty;
    });
    return {
        cartItems: state,
        totalPrice : totalPrice
    }
}

call upon it in the view

<Text style={styles.total}>Totaal: € {this.props.totalPrice}</Text> 

Upvotes: 0

Views: 986

Answers (1)

lecstor
lecstor

Reputation: 5707

You'll want to create a selector for this which you can use from mapStateToProps.

It will look something like

function getTotalCost (state) {
  return state.reduce((result, item) => item.qty * item.price + result, 0); 
}

In your component.. (I'm not sure how your app or state is structured so this will likely need some tweaking)

import { getTotalCost } from "./items/selectors";

const mapStateToProps = state => {
  return {
    totalCost: getTotalCost(state.items)
  }
}

class Component extends React.Component {
  render() {
    const { totalCost } = this props;
    ...
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Component)

Upvotes: 3

Related Questions