Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to dynamically remove item from useState array when function is acticvated

I have a react project. I have a list of items in an array. When an item is selected I have it so that it is automatically added to a useState hook.

setSelectedHomeTypes([...selectedHomeTypes, selected])
console.log(selectedHomeTypes)

Now what I am trying to do and having trouble doing is when the same function is run, I want to dynically remove an item from the list and rerender the flatist that has the items in it. I simply want to do the opposite of adding an item to the list but can not figure out how.

  const updateSelectedHomeTypes = (selected) => {
    let selectedHome = selectedHomeTypes
    if(selectedHome.includes(selected)){
      console.log('found')
      selectedHome.forEach((item, index) => {
        if(item === selected){
          selectedHome.splice(index, 1)
          setSelectedHomeTypes(selectedHome)
          console.log(selectedHomeTypes)
        }
      })
    } else {
      setSelectedHomeTypes([...selectedHomeTypes, selected])
      console.log(selectedHomeTypes)
    }
  }

There is an issue in there and I am not sure what is going on. not sure it there is fundamental issue or if it is not rerending right away based on the new list with the removed item in it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think the problem is that you don’t create a new array and keep the reference to the same array.

try changing let selectedHome = selectedHomeTypes to

let selectedHome = [...selectedHomeTypes]

you can also use indexOf instead of searching for the element.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading