1
  • I have a function to update the state and call another function to update object value in the setState callback method.

  • I also added a debugger on the breakpoint for the setState callback
    method, what I observe is that the value always is the old one.

updateContactPath(path, index) {
    const { contactPaths } = this.state;
    const { setFieldValue } = this.props;
    contactPaths[index] = path;
    this.setState(
      {
        contactPaths,
      },
      () => setFieldValue('contactPaths', contactPaths),
    );
  }
Abhisar Tripathi
  • 1,569
  • 10
  • 21
  • 1
    Does this answer your question? [Correct modification of state arrays in ReactJS](https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs) – Drew Reese Jan 02 '20 at 08:47
  • You mutate the `contactPaths` array but then setState with the same old array reference. You need to setState with a new array object which involves copying the old array *then* mutating the index with the new path. – Drew Reese Jan 02 '20 at 08:49
  • @DrewReese I don't think so. Actually, line 7, I can get the latest contactPaths, but line 9, the contactPaths in the callback function is the old values. – xixiaoshi124 Jan 02 '20 at 08:53
  • @DrewReese you mean like this? ``` updateContactPath(path, index) { const { contactPaths } = this.state; const { setFieldValue } = this.props; const updatedContactPaths = [...contactPaths]; updatedContactPaths[index] = path; this.setState( { contactPaths, }, () => setFieldValue('contactPaths', updatedContactPaths), ); } ``` – xixiaoshi124 Jan 02 '20 at 08:54
  • Don't mutate state, create a new copy, edit it then set that to new state. Or just create a new one directly in the `setState` call. Something like `this.setState({ contactPaths: contactPaths.map((p,i) => index === i ? path : p)})` and finally, in the callback log `this.state.contactPaths` – Jayce444 Jan 02 '20 at 08:56
  • Yes, it is the old (current) value of `contactPaths` which you destructured from state and is saved in the enclosure of your function. If you want the new `contactPaths` state value then in the setState callback you need to access it via `this.state.contactPaths`. – Drew Reese Jan 02 '20 at 08:58

1 Answers1

1

We can do something like this to ensure updated state -:

updateContactPath(path, index) {
    const { contactPaths } = this.state;
    const { setFieldValue } = this.props;
    this.setState(
      {
        [...contactPaths, [index]: path],
      },
      () => setFieldValue('contactPaths', this.state.contactPaths),
    );
  }
Abhisar Tripathi
  • 1,569
  • 10
  • 21