Ad

React JS: SetState Is Late On Last Input

- 1 answer

I'm sorry, if I can't explain my problem properly because english is not my main language.

I create a form component (written in es6) something like this:

class Form extends React.Component {
  constructor(...args) {
    super(args);
    this.state = { input: '' };
  }

  render() {
    return (
      <form>
         <input
           type="text"
           onChange={this.onInputChange.bind(this)}
         />
      </form>
    );
  }

  onInputChange(e) {
    this.setState({ input: e.target.value });
    console.log(`state: ${this.state}, value: ${e.target.value}`); // this is my checking
  }
}

You see the line where I do console.log? Now, when I try to type something on the browser:

// I type this: my word
// on every character input, the output is:

// state: , value: m
// state: m, value: my
// state: my, value: my 
// state: my , value: my w
// state: my w, value: my wo
// state: my wo, value: my wor
// state: my wor, value: my word

// I do backspace
// state: my word, value: my wor
// state: my wor, value: my wo
// state: my wo, value: my w
// state: my w, value: my 
// state: my , value: my
// state: my, value: m
// state: m, value: 

See? The state is late one character on each input. This is not good for validating the input length. What did I do wrong there? Or, did I miss something?

Ad

Answer

Use a callback on the setState method.

onInputChange(e) {
    this.setState({ input: e.target.value }, () => {
        console.log(`state: ${this.state}, value: ${e.target.value}`);
    });
}

From the docs:

The second (optional) parameter is a callback function that will be executed once setState is completed and the component is re-rendered.

Ad
source: stackoverflow.com
Ad