0

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,

Juan Herrero Diaz
  • 833
  • 1
  • 7
  • 17
  • 1
    You need to wait until the user stops typing, set a timeout for the onChange event to make sure they aren't still typing, example here: https://stackoverflow.com/questions/42217121/searching-in-react-when-user-stops-typing . Basically you set a state value for when the user is typing, and when they are not. Make sure to bind the change too. – ABC Mar 10 '19 at 21:47
  • 1
    search for `functional setState`. You seem to be using callback method as well once value is set, you probably need to combine multiple things in one. Read from next state value and then once set, probably make a server call but also tie in some sort of mechanism to cancel it if user entered another value by some sort of timeout/cleartimeout – Rikin Mar 10 '19 at 21:57

0 Answers0