javascript – React/JS async operations within onChange callback changes event data

I just ran into this curious behavior that I can’t explain. In my React app I have the following onChange callback for when value changes within an input.

const onInputChange = useCallback(async (e: ChangeEvent) => {
    console.log('before: ' + e.target.value);

    await doAsyncThing();

    console.log('after: ' + e.target.value);
}, [])

And I noticed that after calling doAsyncThing() the contents of e.target.value are gone; this value is now just an empty string whereas before it was something else. It will show something like:

before: a
after:

Is there some nuance I am missing with doing asynchronous operations within onChange callbacks?

The implementation of doAsyncThing here does not matter. It is not manipulating anything. It does nothing – which is why I was confused to see this.

async function doAsyncThing(text: string): Promise {
    return []
}

Here is a reproducer that showcases the behavior.

Read more here: Source link