0

Trying to figure out why the following:

handleChange = event => {
    console.log(event.target.id, event.target.value)
    this.setState({
        [event.target.id]: event.target.value
    });
    console.log("New state: ", this.state.buyin)
};

Logs "undefined"? The first log is "buyin", (whatever I type in the box) Not sure what I am doing wrong. Any help is much appreciated!

Greetings,

Bram

Tholle
  • 108,070
  • 19
  • 198
  • 189
Bram Wesselink
  • 127
  • 1
  • 1
  • 6

1 Answers1

2

setState is asynchronous, so this.state.buyin will not be set until the state has been updated.

You can use the second argument to setState which is a callback function that is run when the state has been updated.

handleChange = event => {
  console.log(event.target.id, event.target.value);
  this.setState(
    {
      [event.target.id]: event.target.value
    },
    () => console.log("New state: ", this.state)
  );
};
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • That gave some enlightment, cheers for that. But I still get the undefined error? – Bram Wesselink Aug 05 '18 at 14:22
  • @BramWesselink I see. I might have misunderstood your question. Do you think you could elaborate a bit more about what you mean? Could you include your entire component in the question? Do you mean that what you have written in the input is `buyin`? That is the value that the `id` key will have. The state will not have a `buyin` key if that's the case. You can log just `this.state` to see what I mean. – Tholle Aug 05 '18 at 14:24
  • 1
    Well, I just found out I retarded. The "this.state.buyin" is nothing, its this.state.buyin_price. But you still helped me alot with your awnser! It tackled the root of the problem, cheers for that. – Bram Wesselink Aug 05 '18 at 14:25