So I have 2 buttons for adding an item into a cart. The item has 2 prices(1/2kg price and 1kg price). I want when the 1/2kg button is clicked, it adds the item with the 1/2kg price and when the 1kg button is clicked, it adds an item with the 1kg price. So far both buttons add the 1/2kg price because that is the only price I had until they decided to add 1kg of the item. Here is my code below:
PS: price is the 1/2kg price and price2 is the 1kg price.
const CollectionItem = ({ item, addItem }) => {
const { name, price, price2, imageUrl } = item;
return (
<div className="collection-item">
<div className="image" style={{ backgroundImage: `url(${imageUrl})` }} />
<div className="collection-footer">
<span className="name">{name}</span>
<div className="prices">
<strong>
<span className="price">{price}</span>
</strong>
<strong>
<span className="price2">{price2}</span>
</strong>
</div>
</div>
<div className="add-buttons">
<CustomButton
className="custom-button"
onClick={() => addItem(item, 'price')}
inverted
>
Add 1/2kg
</CustomButton>
<CustomButton
className="custom-button"
onClick={() => addItem(item, 'price2')}
inverted
>
Add 1kg
</CustomButton>
</div>
</div>
);
};
const mapDispatchToProps = (dispatch) => ({
addItem: (item) => dispatch(addItem(item)),
});
The addItem is an action creator I used to update my reducer which uses the function below from a cartUtils file I created to update:
export const addItemToCart = (cartItems, cartItemToAdd) => {
const existingCartItem = cartItems.find(
(cartItem) => cartItem.id === cartItemToAdd.id
);
if (existingCartItem) {
return cartItems.map((cartItem) =>
cartItem.id === cartItemToAdd.id
? { ...cartItem, quantity: cartItem.quantity + 1 }
: cartItem
);
}
return [...cartItems, { ...cartItemToAdd, quantity: 1 }];
};
my action is:
export const addItem = (item) => ({
type: CartActionTypes.ADD_ITEMS,
payload: item,
});
my reducer is:
case CartActionTypes.ADD_ITEMS:
return {
...state,
cartItems: addItemToCart(state.cartItems, action.payload),
};
I hope you good people can help me!