Michael
Michael

Reputation: 987

which of these two methods are better to manipulate state?

When changing State in React which one of these would be the preferred way ( or is there no preferred way )

1)

handleDeleteOption(optionToRemove){

this.setState((prevState)=>({
options: prevState.options.filter((option)=>{
  return optionToRemove !== option    })
}))
}

or

2)

handleDeleteOption(option){

this.setState((prevState)=>{
  const newArray = [...prevState.options]
  newArray.splice(newArray.indexOf(option), 1) 
  return{
    options: newArray
  }
})
}

thank you !

Upvotes: 0

Views: 55

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85653

There's also:

this.setState({
 options: [...this.state.options.splice(optionIndex, 1)]
})

A shorter and cleaner way.

Upvotes: 0

Related Questions