Paul Paul - 27 days ago 10
React JSX Question

OnChange form validation react

I encounter a problem with my form validation in react that I don't know how to resolve, here he's :

I want to check if two inputs are same, for example if two mail input are equal to check if the user didn't misspelled his mail but I want a dynamic validation, when the user is writing, check meanwhile.

There is my code :

https://codesandbox.io/s/1v4xxqjzo3

Open the console and start writing in input, and you will see in the OnChange function that both state are never equal because it's like the Onchange function is updating not enough fast, but if I put a setTimeout , it will work because the states are complete.

Answer Source

setState actions are asynchronous.

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

You should use setState callback function to compare inputs values:

onChangeInput(e) {
    const { name, value } = e.target;
    this.setState({
      [name]: value
    }, () => console.log(this.state.mail === this.state.confMail));
  }