Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Value is not written to this.state

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);
            }}
        />
    );
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading