In my react app, I have multiple categories, under each categories I have multiple options. I am trying to write a function to handle toggling the selections. for example:
const initialState=[{id: "fruit", items:["apple", "banana"]}, {id: "veggie", items:["cucumber"]}]
const [selectedItems, setSelectedItems] =useState(initialState)
If I click the banana, the result should be:
[{id: "fruit", items:["apple"]}, {id: "veggie", items:["cucumber"]}]
If I click another fruit, for example, peach, the result should be:
[{id: "fruit", items:["apple", "banana", "peach"]}, {id: "veggie", items:["cucumber"]}]
If I click chicken, the result should be:
[{id: "fruit", items:["apple", "banana"]}, {id: "veggie", items:["cucumber"]}, {id: "meat", items: ["chicken"]}]
I have a toggle handler like this:
function toggle(changed: string, id: string) {
if (selectedItems.find((cat) => cat.id === id)) {
//toggle
} else {
setSelectedItems([
...selectedItems,
{ id: id, items: [changed] },
])
}
}
I am struggling at the toggle part to handle the existing objects. Any help? Thanks.