0

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>
Neelam
  • 31
  • 5
  • 1
    You're using `.pop`, which is _always_ going to [pop the last element off the stack](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) no matter what arguments you give it, because it doesn't take arguments. (There is no such thing as `.pop(action.payload)`, that argument gets ignored.) If you want to remove one or more elements at a specific position, [use `.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice). – Mike 'Pomax' Kamermans Jun 29 '23 at 16:26
  • @Mike'Pomax'Kamermans Thanks, this worked!! – Neelam Jun 29 '23 at 16:55

0 Answers0