So, I am trying to toggle a button to add and remove a product from the wishlist. This works for the most part, but when I try to remove a product the last product added gets removed instead of the one I clicked. Any help?
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
wishlistItems: localStorage.getItem("wishlistItems")
? JSON.parse(localStorage.getItem("wishlistItems"))
: [],
wishlistTotalQuantity: 0,
};
const wishlistSlice = createSlice({
name: "wishlist",
initialState,
reducers: {
toggleItem(state, action) {
const itemIndex = state.wishlistItems.findIndex(
(item) => item.id === action.payload.id
);
if (itemIndex >= 0) {
state.wishlistItems.pop(action.payload);
localStorage.removeItem(
"wishlistItems",
JSON.stringify(action.payload)
);
console.log(JSON.stringify(action.payload));
} else {
const tempProd = { ...action.payload, wishlistQuantity: 1 };
state.wishlistItems.push(tempProd);
}
localStorage.setItem(
"wishlistItems",
JSON.stringify(state.wishlistItems)
);
},
},
});
export const { toggleItem } = wishlistSlice.actions;
export default wishlistSlice.reducer;
This where I use it:
function toggleWishlistHandler(product) {
dispatch(toggleItem(product));
}
<div
className={`${classes.addWishlist} ${classes.icon}`}
onClick={() => toggleWishlistHandler(props.product)}
>
<i className="fa-solid fa-heart"></i>
</div>