React form onChange->setState one step behind

There is a much simpler way to do this, setState(updater, callback) is an async function and it takes the callback as second argument,

Simply pass the handleSubmit as a callback to setState method, this way after setState is complete only handleSubmit will get executed.

For eg.

handleChange: function(e) {
    console.log(e.target.value);
    this.setState({message: e.target.value}, this.handleSubmit);
}

Try to change the handleChange() method like above and it will work.

for syntax of using setState check this link


with setState hook

useEffect(() => {
    your code...
}, [yourState]);

I was pulling my hair out for like an hour because of this so I decided to share... If your callback is still one step behind and seemingly not working, ensure you don't CALL the function with parenthesis... Just pass it in. Rookie mistake.

RIGHT:

handleChange: function(e) {
    console.log(e.target.value);
    this.setState({message: e.target.value}, this.handleSubmit);
}

VS

WRONG:

handleChange: function(e) {
    console.log(e.target.value);
    this.setState({message: e.target.value}, this.handleSubmit());
}

A call to setState isn't synchronous. It creates a "pending state transition." (See here for more details). You should explicitly pass the new input value as part of the event being raised (like to handleSubmit in your example).

See this example.

handleSubmit: function(txt) {
    this.props.onChange(txt);
},
handleChange: function(e) {
    var value = e.target.value;
    this.setState({message: value});
    this.handleSubmit(value);
},