thoerni
thoerni

Reputation: 555

React SetState Function Call not working inside if statement

Heres my (simplified) code:

import { useEffect, useState } from "react"

const Component = () => {
    const [disabled, disableInput] = useState(false)

    useEffect(() =>  {
        console.log("Variable Got Changed")
    }, [disabled])
 
    const onSubmit = (e) => {
        // disableInput(true) // Works
        if (e.key === "Enter") {
            disableInput(true) // Does not work
            console.log("This if statement Works!")
            ...
            disableInput(false) // Does not work
        }
        // disableInput(false) // Works
    }

    return(
        <input [...] onKeyDown={onSubmit} disabled={disabled}/>
    )
}

My problem: Whenever I call disbaleInput() INSIDE the if (e.key === "Enter") statement, it doesn't work. If i put it before the if-statement (still inside the onSubmit function), it does work.

There is no similarly named variable or any interfering naming.

Output, disableInput() call outside of if-statement:

This if Statement Works
Variable got Changed // Logs later due to setState delay

Output, disableInput() call inside of if-statement:

This if Statement Works

I have absolutely no idea what I'm doing wrong.

Upvotes: 0

Views: 626

Answers (1)

Prince Mittal
Prince Mittal

Reputation: 326

There is no problem with the if statement it is working and the state is also getting toggled. But the issue here is you are toggling the disabled to true and then false in the same statement. So what happens, in this case, is that useEffect does not actively “watch” for changes. When you call useEffect in your component, this is effectively queuing or scheduling an effect to maybe run, after the render is done.

After rendering finishes, useEffect will check the list of dependency values against the values from the last render and will call your effect function if any one of them has changed.

But here the value is toggled back to false again before the render could have happened and that's why the useEffect when checking for the changes it doesn't find any and that's why it doesn't console log. Try giving a little timeout to state toggling to false or comment it out for testing purposes.

I have used your code and updated here check it out.

Upvotes: 2

Related Questions