Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS: setState is late on last input

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?

like image 862
Mas Bagol Avatar asked Jan 24 '16 10:01

Mas Bagol


1 Answers

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.

like image 119
villeaka Avatar answered Oct 26 '22 10:10

villeaka