Marko
Marko

Reputation: 545

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!

Upvotes: 7

Views: 11828

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371019

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)
  ]);
}

Upvotes: 15

Related Questions