problem with removing item from an array in ReactJs

Viewed 49

so im building a chess game in react, and i've been working on this notification thing, when the player click their pieces when it's not their turn, a notification should pop-up and say it's the other player's turn.

Each notification box has a button to remove it, but the problem is when i click the last box, all of the other boxes disappear!!, which is not the case when i click the first one, it only remove the one i clicked

here is my code

const [Turn, setTurn] = React.useState<turnType>({
  turn: "White",
  notifications: [],
  id: 0,
});

the chunk responsible for adding new notifications

const handleClick = (id: string) => {
  // only allow the player to click when its their turn, if not add a notification
  if (State[id].color != Turn.turn) {
    setTurn({
      ...Turn,
      notifications: [
        ...Turn.notifications,
        [
          Turn.id,
          <TurnMsg
            key={Turn.id.toString()}
            turn={Turn.turn}
            handleClick={() => {handleRemoveNotification(Turn.id)}}
          />,
        ],
      ],
      id: Turn.id + 1,
    });
  } else {
    // .....
  }

the remove function (newNotifications is just for debugging purposes)

const handleRemoveNotification = (id: number) => {
  let newNotifications = [...Turn.notifications];
  newNotifications = newNotifications.filter((component: any) => {
    console.log("filter loop");
    return component[0] != id;
  });
  setTurn({
    ...Turn,
    notifications: newNotifications,
  });
};

1 Answers

update: i fixed it by doing this instead

const handleRemoveNotification = (id: number) => {
  setTurn((prevValue) => {
    return {
      ...prevValue,
      notifications: prevValue.notifications.filter((arr) => arr[0] != id),
    };
  });
};

i guess using Turn.notifications does some weird stuff

Related