Reputation: 640
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.
Upvotes: 1
Views: 62
Reputation: 3507
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.
Upvotes: 2