1

I have a simple react form, for which I have an async function used on the "onBlur" event of one of the fields. I wanted to check an info in the backend and then update some fields based on the response.

The thing is that setting the states are behaving really strange. It seems sometimes it populates it, and sometimes not. Do I need to do something "special" to set states in an async function?

async function handleEmailBlur(event: ChangeEvent<HTMLInputElement>) {
. . .
                        const {id} = data[0]
                        let toSave = data[0]
                        delete toSave.id
                        const toSaveC = toSave

                        console.log("===> To Save")
                        console.log(toSave)

                        setId(id)
                        setRecoveredData({...toSaveC})

                        console.log("===> Recovered Data")
                        console.log(recoveredData)
. . . 
}

In this example, although toSaveC has data, with the same field names, RecoveredData shows no data in the end.

1
  • You are logging a stale closure log it outside the handleEmailBlur function and it'll be fine Commented Jun 13, 2020 at 19:45

1 Answer 1

2

Because react update state asynchronously, use useEffect hook to check state change like this:

useEffect(()=>console.log(recoveredData),[recoveredData])

this effect will fire when recoveredData change.

Sign up to request clarification or add additional context in comments.

1 Comment

Great, tks! I wasn't sure this was the correct way to do that!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.