I have an array of objects as a state variable. I am trying to write a function that changes a field in one of the objects.
interface IItem{
id: string,
selected: boolean
}
const [array, setArray] = useState<IItem[]>([])
const toggleItem = (id : string) => {
const item = array.find(i => i.id === id)
if (item) {
const copy = {...item, selected: !!item.selected}
setArray(array.map(i => i.id === id ? copy : i))
}
}
The code works, but it looks too complex for this. Is there a way to simplify? (Note, that the order of the items in the array matters).