I am looking for a way to convert this classic js function to an immutable one for use in a useState component. It checks if the id of an item is within an array, if it is, it removes it,
else it adds it.
Classic function:
const addOrRemove = (array, item) => {
array.indexOf(item) === -1 ? array.push(item) : array.splice(array.indexOf(item), 1);
}
React function:
array.indexOf(item) === -1 ? setArray(array=>[...array, item]) : setArray(array.filter(item=>item.id !item.id)
Few questions: is it correct? i.e. does it achieve to not mutate state? can it be optimized ? is there a way to do it better a whole different way?
Thanks a lot