State updates one step behind

I have an input box and an onChange function that updates the state with whatever gets typed into the input box. However, when I console.log the state, it starts off as a space even though I may have started typing.

For example, I may have inputted “hello” but the console would show "hell"and has not updated the last letter until I type in another letter…

That may not make sense but does anyone have any ideas?

I can’t know for sure without seeing your code, but …

This very thing often happens because of a misunderstanding of setState. It is not synchronous. In other words, the app may move on and work on the next step without any guarantee that setState has finished. So:

this.setState({ count: this.state.count + 1 });
console.log(this.state.count);

That console will run before setState has finished so it will show the old value.

Fortunately, setState takes a callback function as a second parameter that is guaranteed to run after setState is done.

this.setState(
  { count: this.state.count + 1 },
  () => console.log(this.state.count),
);

Ah this helps a lot, I have advanced in my code lol
Screenshot 2020-11-17 at 17.06.39 Screenshot 2020-11-17 at 17.06.44
So the console is updated as desired. But what if I want to then perform a regex function on the updated state…? Pass the regex function through as the callback…?

I don’t understand what you mean by, “But what if I want to then perform a regex function on the updated state…?”

Do you mean to affect the output on the screen or do you want it to affect what is saved into state?

I have decided to turn away from regex at this point, saw an easier path :man_facepalming: