Home > front end >  How to dynamically remove item from useState array when function is acticvated
How to dynamically remove item from useState array when function is acticvated

Time:08-24

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.

CodePudding user response:

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.

CodePudding user response:

You are mutating state which is really bad, you need to create new array and then set state:

const updateSelectedHomeTypes = (selected) => {
    if(selectedHomeTypes.includes(selected)){
      const homeTypesCopy = [...selectedHomeTypes]
      const foundIdx = homeTypesCopy.findIndex(item => item === selected)
      if (foundIdx) {
        // it can be shortened
        const newState = selectedHomeTypes.filter(item => item !== selected)
        setSelectedHomeTypes(newState)
      }
    } else {
      setSelectedHomeTypes([...selectedHomeTypes, selected])
    }
  }
  • Related