简体   繁体   中英

Remove item from an array (useState Hook)

Have a useState hook like so:

const [array, updateArray] = useState([])

I know you can add items to the array using a spread operator like so.. (where item is whats being added)

updateArray(array => [...array, item])

how would you remove something from this array? Assuming you have the name of that array item. (remove based off value not index)

Thank you!

If you have a reference to the exact value that was inserted previously (say it's stored in a variable called itemToRemove ), you can .filter it out:

updateArray(array.filter(item => item !== itemToRemove));

This works for both primitives and objects, but it's extremely strange to have an exact reference to an object currently in state. For objects, usually what you'll do is you'll need to figure out a way to identify the index of the element in state, probably with findIndex on a unique property, after which you'd set the new state to the array without that index, something like the following:

// say that the array contains objects with a unique 'id' property
// and you need to remove the item with the id of idToRemove
const index = array.findIndex(({ id }) => id === idToRemove);
if (index !== -1) {
  updateArray([
    ...array.slice(0, index),
    ...array.slice(index + 1)
  ]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM