0

I made a simple react controlled input that store the value in a state and i dont understand why when i press a key for the first time the console log shows "".

Here is my code


class Form extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      value: "",
    };
  }

  handleForm = (e) => {
    console.log("test");

    e.preventDefault();
  };

  handleUsername = (e) => {
    this.setState({ value: e.target.value });

    console.log(this.state);
  };

  render() {
    return (
      <>
        <div>
          <form onSubmit={this.handleForm}>
            <input
              onChange={this.handleUsername}
              type="text"
              placeholder="username"
              value={this.state.value}
            />
            <input type="submit" />
          </form>
        </div>
      </>
    );
  }
}

export default Form;
GRIND
  • 39
  • 8
  • which console.log? and why are you surprised ? – Red Baron Jun 12 '20 at 15:48
  • the console log that give me the value of the state – GRIND Jun 12 '20 at 15:49
  • why's that surprising ? it's attached to `handleUsername` on change? – Red Baron Jun 12 '20 at 15:50
  • if i want to make a login form for a user if his name is like wasd the code will get only the asd or smth like this so i need to fix this – GRIND Jun 12 '20 at 15:52
  • Your code looks like it will satisfy those requirements already. I don't believe it will miss the first letter as you assert. You are only seeing that behavior because of the async nature of `setState`. If you add something like `console.log(this.state)` in your `handleForm` function, you will see that the full text of the input was captured when the form is submitted. – CRice Jun 12 '20 at 15:55
  • State take a few moments to update, if you want to check state updates use componentDidUpdate() or the useEffect hook if you want to use the hooks API. – Rodrigo Jun 12 '20 at 15:55
  • Thanks now i understand this form works fine but is a like a delay problem on console log thanks a lot – GRIND Jun 12 '20 at 15:57
  • `setState` is async so if you want to check value after the update then you can use a callback. You can do this `this.setState({value: e.target.value}, () => console.log(this.state))` – Darshil Mehta Jun 12 '20 at 16:00
  • i already put the console.log(this.state.value); inside the handleForm function and i get the good valuea thanks – GRIND Jun 12 '20 at 16:02

0 Answers0