Praveen Verma
Praveen Verma

Reputation: 144

Modifying nested state fails to update

Why setState is not working for me?

On change event, I am setting a state for array.

handleonChange(x) {
    var newArray = ['Hello', 'Dear'];

    const clonedState = Object.assign({}, this.state);

    clonedState.trans.value = x;
    clonedState.accList = newArray

    this.setState(clonedState);
}

It updates the trans.value but accList does not set.

Upvotes: 0

Views: 41

Answers (1)

aunsal
aunsal

Reputation: 46

why not just try setting state with this syntax (this way you won't have to clone the object, just declare how you want the state to be mutated)

this.setState(previousState => {
  trans:
    {
      ...previousState.trans,
      value: x,
    },
  accList: newArray
});

Upvotes: 2

Related Questions