1

Sandbox example:

https://codesandbox.io/s/207ml94zj0

The offending bit of code:

  handleChange(e) {
    console.log(e.target.value);
    console.log("state before", this.state);
    let a = this.state.tranches.slice(); //Clone the state
    a[0].start = e.target.value;
    a[0].end = 5;
    console.log("state after", this.state);
    this.setState({ tranches: a });
  }

If I just reproduce this as some pure javascript:

const state = {
  tranches: [{
    start: "foo",
    end: 1
  }]
}

const value = "bar";

console.log("state before", state);
let a = state.tranches.slice(); //Clone the state
a[0].start = value;
a[0].end = 5;
console.log("state after", state);

We can see that the value of state is mutated between state before and state after.

Yet in the sandbox example - that isn't the case.

And actually, what's happening is what's being printed to the console in the React example, is the value of the state after the code has run.

Why is that the case?

dwjohnston
  • 11,163
  • 32
  • 99
  • 194
  • Check your browser console. The stack snippet console deep examines the object *immediately*, and logs all of its properties, but the browser console only saves a reference to the object, which, if expanded, will show its *new* value, not the old value (it doesn't save a deep clone of the object to display). It's pretty counter-intuitive. Try using `JSON.stringify` instead in the codesandbox link – CertainPerformance May 15 '19 at 10:41
  • @CertainPerformance Fantastic, thanks. – dwjohnston May 15 '19 at 10:42

0 Answers0