0

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?

zmag
  • 7,825
  • 12
  • 32
  • 42

2 Answers2

6

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)
  });
};
zmag
  • 7,825
  • 12
  • 32
  • 42
0

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.