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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With