'How to filter and delete an item by using redux toolkit
When I click the delete button on each item, I want to remove the item with a filter. But I don't know how to solve it correctly. I'm a bit confused at this point. hope someone can explain this. Thanks a lot.
cartSlice.js
const cartSlice = createSlice({
name: 'cart',
initialState:{
products: [],
quantity: 0,
total: 0,
},
reducers: {
deleteItem: (state, action) => {
//filter right here
state.products = action.payload.idItem;
state.quantity -= 1;
state.total -= action.payload.price * action.payload.quantity;
},
},
});
Cart.jsx
const Cart = (props) => {
const dispatch = useDispatch();
const cart = useSelector((state) => state.cart);
const items = useSelector((state) => state.cart.products);
const handleDeleteItem = (idItem, price, quantity) => {
const filter = items.filter((item) => item.itemId !== idItem);
console.log('idItem', idItem);
console.log('filter', filter);
dispatch(deleteItem({ idItem, price, quantity }));
};
return (
<>
{cart.products.map((product) => (
<tr className={styles.body} key={product._id}>
<td className={styles.column}>
<span className={styles.quantity}>{product.quantity}</span>
</td>
<td className={styles.column}>
<span className={styles.total}>${product.price * product.quantity}</span>
</td>
<td className={styles.column}>
<button
onClick={() => handleDeleteItem(product.idItem, product.price, product.quantity)}
className={styles.deleteItem}
>
Delete
</button>
</td>
</tr>
))}
</>
);
};
export default Cart;
Solution 1:[1]
In your reducer you say, the new product is the idItem key :
reducers: {
deleteItem: (state, action) => {
//filter right here
state.products = action.payload.idItem;
state.quantity -= 1;
state.total -= action.payload.price * action.payload.quantity;
},
},
But in your cart, you don't pass the filter as parameters :
const handleDeleteItem = (idItem, price, quantity) => {
const filter = items.filter((item) => item.itemId !== idItem);
console.log('idItem', idItem);
console.log('filter', filter);
dispatch(deleteItem({ idItem, price, quantity }));
};
Shouldn't it be
const handleDeleteItem = (idItem, price, quantity) => {
const filter = items.filter((item) => item.itemId !== idItem);
dispatch(deleteItem({ idItem: filter, price, quantity }));
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BENARD Patrick |
