Austin Roose
Austin Roose

Reputation: 69

State in React not changing with setState method

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

Upvotes: 1

Views: 54

Answers (2)

Mohammad Basit
Mohammad Basit

Reputation: 575

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()

Upvotes: 0

Nam Bui
Nam Bui

Reputation: 1361

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

Upvotes: 2

Related Questions