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

how to access state value right after setting the same state variable in another function in react.js class component

submit = () => {
   this.checkValidation();
   console.log(this.state.isError) //this is not giving updated value
}

checkValidation = () => {
this.setState({
isError: true
})
}

>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

You can callback funtion to access the updated state right after setting it,

this.setState({ isError: true }, this.logState)

 logState = () => {
    console.log(this.state.isError)
  };

In your case you can either move the setting of state inside the submit function or return the updated the updated value from checkValidation function and then set the state within submit function :

submit = () => {
   this.checkValidation();
   setState(
    { isError: true },
    () => console.log(this.state.isError)
  );
}
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