user12200634
user12200634

Reputation:

React function isn't behaving as its expected to

Heres a function from my react app:

handleSubmit(evt) {
  evt.preventDefault();
  this.setState({
    width: "",
    height: "",
    color: ""
  });
  console.log(this.state)
};

In my input, I set the value of input to the width, height and color. this handleSubmit function is happens when a form in filled.

But I have set the state via setState before the console.log line. So this will replace the values from the form, before the console.log is called. I should get

{width :" ", height :" ", color :" "} 

But instead, I get the value that was set by the input. But it seems like setState is only working when the full function is done, not before the log. Why?

Upvotes: 0

Views: 101

Answers (2)

Paul Terry
Paul Terry

Reputation: 1

You can use functional setState rather than passing an object. Instead you can pass a function to setState which takes the current state and props as arguments, this function returns an object which will be merged into the old state.

For example,

this.setState((state, props) => {
    return {
        counter: state.counter + 1
    }
});

Calls to setState get queued and then executed in the order they were called. When they are executed the function receives the latest state instead of receiving old state.

Upvotes: 0

zmag
zmag

Reputation: 8241

But it seems like setState is only working when the full function is done, not before the log. Why?

setState doesn't change the state immediately. Ref: https://reactjs.org/docs/react-component.html#setstate

If you want to do something right after the state change, use a callback function.

handleSubmit(evt) {
  evt.preventDefault();
  this.setState({
    width: "",
    height: "",
    color: ""
  }, () => {
    console.log(this.state)
  });
};

Upvotes: 6

Related Questions