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

Why SetState not executed on componentDidMount

I want to update a state in ComponentDidMount but the setState function is not being executed

ComponentDidMount() {
    if (this.props.location.search.includes("?token")) {
      const email = getQueryVariable(this.props.location.search, "email");
      const token = getQueryVariable(this.props.location.search, "token");
      if (this.state.showValidationModal === false) {
        console.log("Before",this.state.showValidationModal);
        this.setState({
          showValidationModal:true
        })
        console.log("After",this.state.showValidationModal);

      }
    }
  }

when the application gets mounted the result of both showValidationModal log are false

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

>Solution :

setState is an async operation, it doesn’t update the state immediately, But the setState callback, has the last instance value from the state, So.

ComponentDidMount() {
if (this.props.location.search.includes("?token")) {
  const email = getQueryVariable(this.props.location.search, "email");
  const token = getQueryVariable(this.props.location.search, "token");
  if (this.state.showValidationModal === false) {
    console.log("Before",this.state.showValidationModal);
    this.setState({
      showValidationModal:true
    })
    // here you get the latest value of showValidationModal state
    this.setState(prevState => console.log(prevState.showValidationModal))

    // here you get the old value.
    console.log("After",this.state.showValidationModal);

  }
}
}
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