After you create everything, you export it together with connect
.
interface PassedProps {
productId: number;
}
interface StateToProps {
addedProductIds: number[];
quantityById: { [key: string]: number };
quantity: number;
}
interface DispatchToProps {
addToCart: (productId: number) => void;
removeFromCart: (productId: number) => void;
}
// Needs to be added to src/store:GlobalStore interface with the correct prop name created from the name of the reducer
export interface CartState {
addedProductIds: number[];
quantityById: { [key: string]: number };
}
const mapStateToProps = (globalState: GlobalState): StateToProps => {
const state: CartState = globalState.cart;
return {
addedProductIds: state.addedProductIds,
quantityById: state.quantityById,
quantity: Object.keys(state.quantityById).reduce( (sum: number, key: string) => state.quantityById[key] + sum, 0)
};
};
const mapDispatchToProps = (dispatch: Dispatch<any>): DispatchToProps => {
return {
addToCart: (productId: number) => dispatch({ type: 'ADD_TO_CART', productId } as AddToCartAction),
removeFromCart: (productId: number) => dispatch({ type: 'REMOVE_FROM_CART', productId } as RemoveFromCartAction),
};
}
export type Props = PassedProps & StateToProps & DispatchToProps;
class CartButton extends Component<Props, CartState> {
render() {
const { quantity } = this.props;
return (
<View>
<Text>
{ this.props.addedProductIds.length } type item is in the cart, totals to { quantity } item.
</Text>
<View>
<Button
onPress={this.onPressAdd.bind(this)}
title="Add to Cart"
color="#841584"
/>
<Button
onPress={this.onPressRemove.bind(this)}
title="Removefrom Cart"
color="#841584"
/>
</View>
</View>
);
}
onPressAdd() {
this.props.addToCart(this.props.productId);
}
onPressRemove() {
this.props.removeFromCart(this.props.productId);
}
}
export default connect<StateToProps, DispatchToProps, PassedProps>(mapStateToProps, mapDispatchToProps)(CartButton);
Then you can use it with specifying with the required props to be passed (PassedProps interface):
import CartButton from '../components/CartButton';
// ....
render() {
return(<CartButton productId={5} />)
}