Reputation: 35
I'm creating a react native application for e-commerce purposes and am trying to get the cart functionality working. I'm using redux and I am able to add one item at a time to the cart but when I try to delete an item from the cart, all of the same items get deleted. For example, if I have 2 pencils, 3 pens and 4 notebooks in my cart and I click the delete button on one of the notebooks, all 4 notebooks get removed from my cart. I want to be able to only remove one item at a time.
const cartItems = (state = [], action) => {
switch (action.type) {
case 'ADD_TO_CART':
return [...state, action.payload]
case 'REMOVE_FROM_CART':
return state.filter(cartItem => cartItem.id !== action.payload.id)
//return state.filter(cartItem => cartItem !== action.payload.id
//const filteredItems = state.filter((cartItem) => cartItem.id !== action.payload.id);
}
return state
}
export default cartItems
The two lines that are commented out are the other ways I've tried, but ultimately didnt work.
Upvotes: 2
Views: 332
Reputation: 504
This line
return state.filter(cartItem => cartItem.id !== action.payload.id)
Means "return a new array consisting of all state
elements except those which have id
property matching action.payload.id
".
So if there are multiple items with the same id
, all f them will be filtered out.
Since this is just plain JavaScript, you can have any logic here, you just need to return a new array. This, for example, will delete only the first matching element:
let removed = false;
return state.filter(cartItem => {
if (cartItem.id === action.payload.id && !removed) {
removed = true;
return false;
}
return true;
});
A better solution would be to create another identifier for the items in cart, so that the action does not remove the first matching item in the list, but the one the user requested to delete by tapping the delete button.
Upvotes: 2