Here are properties of state object:
const [items, setItems] = useState({
key1: 'apple',
key2: 'watermelon',
key3: 'banana',
});
I wonder, how I can delete specific property from this state object by handling delete?
const handleDelete = (e) => { }
Thanks in advance
Here's one way: duplicate the object (so React notices the change), delete the key (maybe this is the JavaScript feature you were missing), and set the state.
const handleDelete = (e) => {
const newItems = {...items};
delete newItems.key2; // or whichever key you want
setItems(newItems);
}
I'm curious whether there's an Object
helper to do this all in one line.
@Wyck found a cleaner way, which uses the "rest" aspect of destructuring assignment:
const handleDelete = (e) => {
const {key2, ...newItems} = items; // newItems gets all but key2
setItems(newItems);
}
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