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
}
})