useState remove item from array

Viewed 6533

I'm trying to remove an item from an error but it's not working like expected.

Im using state:

  const [actions, setActions] = useState([
    {
      action: "",
      key: ""
    }
  ]);

I have a button to add actions:

    <IconButton
      icon="add"
      bgColor="white"
      iconColor="darkGray"
      onClick={() =>
        setActions([
          ...actions,
          {
            action: "",
            key: ""
          }
        ])
      }
    />

Each row has a delete and I'm trying to use the row index to delete the item in the actions array:

      <IconButton
        disabled={actions.length === 1}
        icon="dash"
        iconColor="red"
        onClick={() => {
          console.log(index);
          setActions(actions => {
            return [...actions.splice(index, 1)];
          });
        }}
      />

https://codesandbox.io/s/actions-selector-n9xb4

2 Answers

Try using filter. It does not modify the existing array and can be used like this:

setActions(prevActions => (
  // Filter out the item with the matching index
  prevActions.filter((value, i) => i !== index)
));
  <IconButton
    disabled={actions.length === 1}
    icon="dash"
    iconColor="red"
    onClick={() => {
      setActions(actions.filter((item, i) => i !== index));
    }}
  />

I tested it in your Codesandbox and it worked

Related