Home > other >  Value is not written to this.state
Value is not written to this.state

Time:07-06

On a React page I have a method by means of which I'm trying to set the state. However, it doesn't seem to work (see the console.log). What am I doing wrong?

editPlan = (cell, row) => {
    return (
        <img
            src={edit}
            alt="edit"
            onClick={() => {

                console.log(row.id);                                     // prints 2

                this.setState({ editId: row.id, openEditModal: true });

                console.log(JSON.stringify(this.state.editId));          // prints "". I would expect 2.
                console.log(JSON.stringify(this.state.openEditModal));   // prints false. I would expect true.

                this.props.getPlan(row.id);
            }}
        />
    );
};

CodePudding user response:

setState works asynchronously -- it just queues up your desired state change and will get to it later to optimize how your component will re-render.

You can pass a callback to the function as the last argument which will be called when the state change has occurred.

this.setState(
  { editId: row.id, openEditModal: true },
  () => {
    console.log(JSON.stringify(this.state.editId));
    console.log(JSON.stringify(this.state.openEditModal));
  }
);

See: https://reactjs.org/docs/react-component.html#setstate

CodePudding user response:

You can try using the state callback function because setState works asynchronously

this.setState({ editId: row.id, openEditModal: true },()=>{
      console.log(JSON.stringify(this.state.editId));          
      console.log(JSON.stringify(this.state.openEditModal));  
      this.props.getPlan(row.id);
  });
  • Related