Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useState remove item from array

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

like image 398
Batman Avatar asked Feb 14 '26 16:02

Batman


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)
));
like image 94
Brian Thompson Avatar answered Feb 16 '26 06:02

Brian Thompson


  <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

like image 24
Luis Montoya Avatar answered Feb 16 '26 05:02

Luis Montoya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!