I’m working on redux project that has add to card button and delete item from card. The delete button isn’t working and when I check with console.log it’s adding item to card. I’m trying to fix it but it’s not working.
I’m adding the code that I have below
import { createSlice } from "@reduxjs/toolkit";
export const slice = createSlice({
name: "recipeCart",
initialState: {
itemsInCart: []
},
reducers: {
addItemToCard: (state, action) => {
const timeId = new Date().getTime()
state.itemsInCart.push({
idFood: timeId,
dishId: action.payload.dish.idFood,
quantity: action.payload.quantity,
totalPrice: action.payload.quantity * action.payload.dish.price
})
},
removeItemFromCart: (state, action) => {
state.itemsInCart = state.itemsInCart.filter(
itemsInCart => itemsInCart.idFood !== action.payload.itemsInCartId
)
}
}
})
export const getTotalPrice = state => {
return state.recipeCart.itemsInCart.reduce((total, itemsInCart) => {
return itemsInCart.totalPrice + total
}, 0)
}
export const getCartItems = state => state.recipeCart.itemsInCart;
export const { addItemToCard, removeItemFromCart } = slice.actions;
export default slice.reducer
import dishesData from "../data/dishesData";
import { removeItemFromCart } from "../redux/cartSliceFood.js";
import { useDispatch } from "react-redux";
const CartItemFood = ({ itemsInCart }) => {
const recipeDishes = dishesData.find(
item => item.idFood === itemsInCart.dishId
)
const dispatch = useDispatch();
console.log(recipeDishes)
return (
<div>
<div className="headerCart">
<div className="container-cart">
<p className="cartPar">{recipeDishes.name}</p>
<p className="cartPar">{itemsInCart.quantity} portion(s)</p>
<p className="cartPar price">
Price: ${recipeDishes.price * itemsInCart.quantity}
</p>
<span
onClick={() => dispatch(removeItemFromCart({
itemsInCartId: itemsInCart.id
}))}
>
<img
className="icon cartPar"
src="https://img.icons8.com/material-outlined/48/000000/trash--v1.png"
alt="icon"
/>
</span>
</div>
</div>
</div>
)
}
export default CartItemFood;
import { configureStore } from '@reduxjs/toolkit';
import dishes from './DessertComponent/redux/dishesSlice';
import cart from './DessertComponent/redux/cartSlice';
import recipeDishes from './FoodComponent/redux/dishesSliceFood';
import recipeCart from './FoodComponent/redux/cartSliceFood'
export const store = configureStore({
reducer: {
dishes: dishes,
cart: cart,
recipeDishes: recipeDishes,
recipeCart: recipeCart
}
})
2
Answers
I think some mistake in
It should be
You are using key idFood, not id.
In your addItemToCard reducer, you’re assigning a unique ID to each item with idFood:
However, when you attempt to delete an item, you’re using itemsInCart.id in your removeItemFromCart dispatch:
The key id doesn’t exist in your cart items; it’s actually idFood. Therefore, you should use itemsInCart.idFood when identifying the item to remove. This mismatch is why the deletion wasn’t working.