0

I've been trying to learn React, and I'm currently building a form app, and i'm trying to test displaying value after I type them on input field. And I seem to get an issue. Example when I type "Ab" the console log shows white space then A and no "b". Is there an explanation to this?

Here is my code

function Text(props) {
  var style = {
    paddingTop: 5,
    margin: 5
  };
  return (
    <div>
      <div style={style}> {props.label} </div>
      <input
        type="text"
        style={style}
        value={props.labelInputText}
        onChange={props.changeHandler}
      />
    </div>
  );
}
class FormApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      firstName: ""
    };
    this.changeHandler = this.changeHandler.bind(this);
  }
  changeHandler(event) {
    this.setState({ firstName: event.target.value });
    console.log(this.state.firstName);
  }

  render() {
    return (
      <div>
        <Text
          label="First Name"
          labelInputText={this.state.firstName}
          changeHandler={this.changeHandler}
        />
      </div>
    );
  }
}

ReactDOM.render(<FormApp/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Ndx
  • 517
  • 2
  • 12
  • 29
  • write it like this it will print the updated state value: `this.setState({ firstName: event.target.value }, () => { console.log(this.state.firstName) } )` – Mayank Shukla Aug 01 '17 at 15:44
  • 1
    It's working! Thank you! setState() is asynchronous so that explains it. – Ndx Aug 01 '17 at 15:48

1 Answers1

0

setState is asynchronous. You can use callback method to get updated state.

changeHandler(event) {
    this.setState({ firstName: event.target.value }, () => 
    console.log(this.state.firstName));
 }
Piyush Dhamecha
  • 1,485
  • 1
  • 13
  • 22