1

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.

1 Answer 1

2
function toggle(changed: string, id: string) {
if (selectedItems.find((cat) => cat.id === id)) {

  const obj = selectedItems.find(x => x.id === id);
  const itemsToProcess = obj.items

  // exist, to remove
  if(itemsToProcess.find(x => x === changed)){
      setSelectedItems([
        // things we don't touch
        ...selectedItems.filter(x => x.id !== id),
        // filtered array 
        {id, items: [...itemsToProcess.filter(i => i !== changed)]}
  ])
  }
  // to add
  else{
    setSelectedItems([
        ...selectedItems.filter(x => x.id !== id),
        {id, items: [...itemsToProcess, changed]}
    ])
  }
} else {
  setSelectedItems([
    ...selectedItems,
    { id: id, items: [changed] },
  ])
}

}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.