Search code examples
reactjstypescriptreduxmaterial-ui

Redux remove reducer filter method not working


I'm trying to remove an item from an array using the filter method like so:

removeDisplate: (state, action: PayloadAction<string>) => {
  console.log(action.payload);
  state.map((item) => {
    console.log(item.name);
  });
  state.filter((item) => item.name !== action.payload);
},

And calling it from my frontend like so:

{cart.map((displate, index) => {
  return (
    <Card
      sx={{
        minHeight: "150px",
        display: "flex",
        padding: "10px",
        gap: "10px",
        backgroundColor: "black",
        margin: "10px",
        position: "relative",
      }}
      key={index}
    >
      <CloseIcon
        sx={{
          position: "absolute",
          top: "10px",
          right: "10px",
          color: "red",
          cursor: "pointer",
        }}
        onClick={() => handleRemoveDisplate(displate.name)}
      />
    </Card>
  );
})}

Both the payload and the name of the item in state are the same as per the console logs, but it's still not removing it from the array, any ideas?


Solution

  • Array.prototype.filter doesn't mutate the array it operates over, it returns a new array with elements failing the predicate callback removed. In the slice reducer you can just return the result of filtering the current state as the next state value.

    removeDisplate: (state, action: PayloadAction<string>) => {
      return state.filter((item) => item.name !== action.payload);
    },
    

    Additionally, since you are mutating this array you'll want to not use the array index as the React key. Use a value that is more intrinsic to the data you are mapping, like id properties.

    Example:

    {cart.map((displate, index) => {
      return (
        <Card
          sx={{
            minHeight: "150px",
            display: "flex",
            padding: "10px",
            gap: "10px",
            backgroundColor: "black",
            margin: "10px",
            position: "relative",
          }}
          key={displate.id} // <-- or any unique property among sibling elements
        >
          <CloseIcon
            sx={{
              position: "absolute",
              top: "10px",
              right: "10px",
              color: "red",
              cursor: "pointer",
            }}
            onClick={() => handleRemoveDisplate(displate.name)}
          />
        </Card>
      );
    })}