0

I want to remove an object of an object in react, what I'm planning to do is get the current state and assign it to a variable, alter that variable, use setState to assigned the altered variable to state. Like this

constructor() {
    super()
    this.state = {
      obj: {
        "0": {
          something: 123
        },
        "1": {
          another_thing: 'abc'
        }
      }
    }
  }

  deleteOneObj(index) {
    let newObjState = this.state.obj[index]
    delete newObjState
  }

  render() {
    return(<h1>hello<br />
      <button onClick={()=>this.deleteOneObj(1)}>
        delete one obj
      </button>
    </h1>)
  }

But delete newObjState doesn't seem to work.

Xie Xie Fang
  • 181
  • 3
  • 9

2 Answers2

1

I would prefer using Object.assign, it's more readable and also creates a new reference of an object:

deleteOneObj(index) {
    let newObjState = Object.assign({}, this.state.obj)
    delete newObjState[index]
    this.setState({obj: newObjState}) 
}
-1

Try something like this:

deleteOneObj(index) {
    let newObjState = JSON.parse(JSON.stringify(this.state.obj))
    delete newObjState[index]
    this.setState({obj: newObjState}) 
  }
mehulmpt
  • 15,861
  • 12
  • 48
  • 88
  • hmm why? is there any alternative which is more descriptive? – Xie Xie Fang Jan 17 '18 at 13:33
  • This mutates the state, which is [bad](https://redux.js.org/recipes/structuring-reducers/prerequisite-concepts#immutable-data-management) (assuming redux here) – Derek Adair Jul 16 '19 at 16:31
  • @DerekAdair this doesn't mutate state. I'm JSON.stringifying the object which returns a string, all reference to the current state is lost. That is one way to deep clone an object – mehulmpt Jul 16 '19 at 16:36