React: state's boolean flag doesn't update fast enough

I keep boolean flag named validationPassed in a state which I use in if statement. If it’s true, I allow axios request to happen. Before that if statement I call doValidation() which has a lot of if statements. If one of them fail, I setState of that boolean flag to false. In setState() I put console.log callback and it seems boolean flag is successfuly set to false but not immediately because if(this.state.validationPassed) passes when it shouldn’t. I’m aware that React state is asynchronous. Tried to use prevState argument to toggle boolean’s value but it didn’t work. How do I make this work? Maybe there’s another way to do validation without boolean flags?

    this.state = {

        validationPassed: true
    }
}

   this.doValidation(usernameFromUser, passwordFromUser)

   if(this.state.validationPassed){

    // axios call
   }

}

doValidation = (username, password) => {

    if(username.trim().length === 0){

          this.setState( {
            validationPassed: false }, () => {console.log(this.state.validationPassed)});
    }

    if(password.trim().length === 0){

          this.setState( {
            validationPassed: false }, () => {console.log(this.state.validationPassed)});
    } 

    if(username.trim().length < 8){

        this.setState( {
            validationPassed: false }, () => {console.log(this.state.validationPassed)});
    }

    if(username.trim().length > 20){

        this.setState( {
            validationPassed: false }, () => {console.log(this.state.validationPassed)});
    }

    if(password.trim().length < 8){

        this.setState( {
            validationPassed: false }, () => {console.log(this.state.validationPassed)});
        } 

    if(new RegExp("^(?!(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,}))").test(password)){

        this.setState( {
            validationPassed: false }, () => {console.log(this.state.validationPassed)});  
    }
}

112 thoughts on “React: state's boolean flag doesn't update fast enough”