I am creating a React component (similar to a textarea) and now I plan to add a feature where the user types text and the letters are processed asynchronously to validate that they are correct (for example, to prevent letters in a phone field). The validation logic can potentially modify them (for example, duplicate letters).
I have the following code in my "onChange" implementation:
_onChange = (event: SyntheticEvent<HTMLInputElement>): void => {
...
this.setState({ value }, () => {
myAsyncCall(param).then(result => {
if (!result.returnCode) {
// If the return code is false, we should not accept the new key.
this.setState({
value: ..,
})
} else {
this.setState({
// Here in result.value I have the potentially modified value.
value: result.value,
})
})
})
}
However, this is not correct, as for example, the user may type very fast and by the time the setState
calls inside the callbacks are executed, the state may be different, potentially overwriting with old content.
Is there any way to solve this problem correctly? I was thinking about getting the current state before calling the this.setState
inside the callbacks, just to make sure I always work with the most recent state, but I don't know if this makes sense, and how it can be done.
Thank you,