1

I am trying to update my state with setState method in one of my functions but state doesn't somehow change. I am also using if statement in that function to tell the setState when to actually change state. I get back correct message in console.log when if statement is true but my state still doesn't change. What could cause the error?

My function and state:

constructor(props) {
    super(props);
    this.state = {
        isregistered: false
    }
}

handleValidate = (validate) => {
    const state1 = this.state
    console.log('state1', state1)
    const validate1 = validate
    console.log('l]plik validate', validate1)
    if ( validate.length != 0){
        this.setState({
            isregistered: true
        })
        console.log('onregatud', this.state.isregistered)
   }
   else{
        console.log('mitteregatud', this.state.isregistered)
   }
}
Austin Roose
  • 69
  • 2
  • 11
  • Please show `render` – cbr Sep 11 '20 at 15:07
  • this function isn't connected to my UI buttons or anything. Handle validate gets called eventually under method componentDidMount and is initiated when user enters that page. – Austin Roose Sep 11 '20 at 15:12
  • Does this answer your question? [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) – cbr Sep 11 '20 at 15:20

2 Answers2

2

It is not an error, setState is asynchronous. If you want to check the state right after a setState you need to pass a callback :

this.setState({myState : newState}, () => console.log(this.state.myState))
Nam Bui
  • 1,251
  • 1
  • 7
  • 5
1

The setState() operation is asynchronous and your console.log() will be executed before the setState() mutates the value of isregistered where you set it from false to true and hence you are not able to see the result.

We can solve this issue by two ways:

  1. By passing a callback function to the setState()

     const handleValidate = (validate) => {
      const state1 = this.state
      const validate1 = validate
       if ( validate.length != 0){
         this.setState(
         { isregistered: true }, 
         () => console.log('callback fired', this.state));
       } else {
         console.log('mitteregatud', this.state.isregistered);
       }
     }
    
  2. By using async-await

    async function handleValidate(validate) {
      const state1 = this.state
      const validate1 = validate
       if ( validate.length != 0){
         await this.setState({ isregistered: true})
         // More code here based on state outside callback
         console.log('onregatud', this.state.isregistered)
       } else {
         console.log('mitteregatud', this.state.isregistered)
       }
    }
    

    Using async-await is cleaner instead of using a callback in setState()

Mohammad Basit
  • 971
  • 6
  • 18