IcanCode
IcanCode

Reputation: 537

When does the state Change occur of a class using setState method?

I have a form which calls the hanldeChange function on onChange event.The function definition is:

handleChange = (e) =>{
    this.setState({
        [e.target.name]:e.target.value
    })
    console.log(`Password:${this.state.password} and ConfirmPassword:${this.state.confirmPassword}`)
    if(this.state.password !== this.state.confirmPassword){
        this.setState({
            passwordError:"Passwords don't match."
        })
    }
    else if(this.state.password === this.state.confirmPassword){
        this.setState({
            passwordError:""
        })
    }

My question is ,Does the state change immediately after the call to setState - "Yes",this is what I think but the above code doesnot work if both Password and confirmPassword are same.

What is going wrong here?

Upvotes: 0

Views: 36

Answers (2)

bonnopc
bonnopc

Reputation: 850

You will get the updated state at the callback of a setState. So your handleChange should be,

handleChange = (e) =>{
    this.setState({
        [e.target.name]:e.target.value
    }, () => {
        if(this.state.password !== this.state.confirmPassword){
            this.setState({
                passwordError:"Passwords don't match."
            })
        }
        else if(this.state.password === this.state.confirmPassword){
            this.setState({
                passwordError:""
            })
        }
    })
    
}

For more info, please visit here

Upvotes: 1

Daniel Stoyanoff
Daniel Stoyanoff

Reputation: 1564

React batches all setState statements that are executed in a single event scope. So in your case, the whole function will be executed and only then react will actually update the state.

This article about React 18 explains it very well: https://github.com/reactwg/react-18/discussions/21

Upvotes: 1

Related Questions