Search code examples
javascriptreactjssetstate

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


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