Categories
React Answers

How to fix React form setState is one step behind onChange?

Spread the love

Sometimes, we want to fix React form setState is one step behind onChange

In this article, we’ll look at how to fix React form setState is one step behind onChange.

How to fix React form setState is one step behind onChange?

To fix React form setState is one step behind onChange, we call setState with an object with the states we want to change and a function that’s called after the states are changed.

For instance, we write

class Comp extends Component {
  //...
  handleChange = (e) => {
    console.log(e.target.value);
    this.setState({ message: e.target.value }, this.handleSubmit);
  };
  //...
}

to call setState with { message: e.target.value } to set the message state to e.target.value.

After the states are set then this.handleSubmit is called.

Conclusion

To fix React form setState is one step behind onChange, we call setState with an object with the states we want to change and a function that’s called after the states are changed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *