0

When Im trying to add objects to a hook inside a component it works fine - kinda. It seems that no matter what i do to get the hook updated with the whole array of selected items. It is always missing the last selected object. This is also when removing object.

So let's say I choose item 1, 2, 5 - Then the hook is missing 5 let's say I choose 1, 2, 4, 5 but then deselect 2 then the hook got all the selected but didnt deselect item 2.

Here is my code..

const [selected, setSelected] = React.useState<string[]>()

React.useEffect(() => {
    const getBrands = async () => {
       const user = await getUser()
       setSelected(user?.brands)
    }
    getBrands()
}
, [])

const toggleSelection = async(item: string) => {
    console.log("clicked: ", item)
        if (selected === undefined){
            setSelected([item])
        }
        if (selected?.includes(item)) {
            setSelected(selected.filter((i) => i !== item))
        } else {
            setSelected([...selected, item])
           
        }
        await updateUser({brands: selected})
 }

And this is the console output:

 clicked:  2
    Updating with  Object {
    "brands": Array [
      "1",
      "3",
      "5",
    ],
    }
clicked:  4
Updating with  Object {
  "brands": Array [
    "1",
    "3",
    "5",
    "2",
  ],

1 Answers1

0

I believe that this question is duplicated please check this link

I hope this work around works for you :

...  
const toggleSelection = (item: string) => {
    console.log("clicked: ", item)
        if (selected === undefined){
            setSelected([item])
        }
        if (selected?.includes(item)) {
            setSelected(selected.filter((i) => i !== item))
        } else {
            setSelected([...selected, item])
           
        }
 }

 useEffect(() => {
   // 'selected' will be updated here
    async function asyncCall() {
     if(selected.length>0)
     await updateUser({brands: selected})
    }
   asyncCall();
  }
 , [selected])
Mortadha Fadhlaoui
  • 388
  • 1
  • 5
  • 16