Reputation: 103
If my state element is duplicated, I want to add a property named "quantity" and make it +1 in each click.
Reducer
case actionTypes.ADD_TO_CART:
const addedItem = state.cart.find(c => c.id === action.payload.id)
if (addedItem) {
return Object.assign({}, addedItem, {quantity: addedItem.quantity++})
}
return {
...state,
cart:
state.cart.findIndex((c) => c.id === action.payload.id) >= 0
? state.cart
: [...state.cart, action.payload]
};
State
cart: []
UI
addToCart(p) {
this.props.actions.addToCart({quantity: 1, p});
}
{products.map((p) => (
<tr key={p.id}>
<th scope="row">{p.id}</th>
<td>{p.productName}</td>
<td>{p.quantityPerUnit}</td>
<td>{p.unitPrice}</td>
<td>{p.unitsInStock}</td>
<td>
<button
onClick={() => this.addToCart(p)}
className="btn btn-danger"
>
Add To Cart
</button>
</td>
</tr>
))}
This is what I tried and failed. I successed preventing duplicate elements in the state but I can't add its quantity property.
For example, I added A item twice. I want to see that A item has gained quantity property and it is 2.
How can I do that ?
Upvotes: 0
Views: 76
Reputation: 7564
You could write your reducer as:
case actionTypes.ADD_TO_CART:
const existingItem = state.cart.find(c => c.id === action.payload.id)
const itemToAdd = existingItem ? {...existingItem, quantity: existingItem.quantity + 1} : action.payload;
return {
...state,
cart:
[...(state.cart.filter((c) => c.id !== action.payload.id)), itemToAdd]
};
and also update the addToCart
function
addToCart(p) {
this.props.actions.addToCart({...p, quantity: 1});
}
Upvotes: 1