React state extend multilevel object not working

state defaults

state = {
        moveType: {
            value: 0,
            open: false,
            completed: false
        }
    };

      

// callback to update the new state

let step = 'moveType';
let val = 3; // new value
let newObj = { ...this.state[step], value: val };
console.log(newObj);
this.setState({[step]: newObj }, function () {console.log(this.state);});

      

console.log(newObj)

shows new values, but this.state

still shows old values. Can you tell me what I am doing wrong?

+3


source to share


1 answer


Setting up a state in a reaction is a pretty sensitive thing. The best practices I've used are always manipulating the object with a manual merge method and using the invocation type this.setState(state => { ... return new state; })

like in this example:

this.setState(state => ({
  ...state,
  [step]: { ...(state[step] || {}), ...newObj },
}), () => console.log(this.state));
      

Run codeHide result


SNIPPET UPDATE Failure

[step]: { ...state[step], ...newObj }

Changed to:



[step]: { ...(state[step] || {}), ...newObj }

To properly deal with cases where the state does not yet have this key step

SNIPPET UPDATE Failure

The point is that when you use this.state

(in let newObj = { ...this.state[step]

) it might be deprecated due to some pending (not yet merged) changes in state that you called just a couple of milliseconds ago.

Thus, I recommend using the: callback method this.setState(state => { ... use state and return new state;})

, which makes sure that used state

has the latest value

+2


source







All Articles