2
  constructor(props) {

    super(props);
    this.state = {
      active: false,
      showSideBar: false,
      className: ""
    }
  }
  componentDidMount() {
    if (this.props.overlay) {
      this.setState({
        className: "wrapper_overlay"
      });
      alert(this.state.className);
    }
    else if (this.props.SideBarWithIcon) {
      this.setState({
        className: "wrapper_clopsed"
      });
    }
  }

I am updating my state with the help of the props but the component is getting props but state is not updating

1

5 Answers 5

4

setState is asynchronous. Just alert in a callback to the method instead.

if (this.props.overlay) {
  this.setState(
    { className: "wrapper_overlay" },
    () => alert(this.state.className);
  );
}

Note: you can, and should, also use shouldComponentUpdate to check for when a setState call completes

3

Since setstate is async in nature so you maynot see updated state in alert. You can use that in callback which will be called once the setstate is done. like this

componentDidMount() {
    if (this.props.overlay) {
      this.setState({
        className: "wrapper_overlay"
      }, ()=> {alert(this.state.className);});
   }
1

State updates may be asynchronous

React may batch multiple setState() calls into a single update for performance.

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

// Wrong
this.setState({
    className: "wrapper_overlay"
  });

To fix it, use a second form of setState() that accepts a function rather than an object.

// Correct
this.setState((state, props) => ({
  className: "wrapper_overlay"
}));

or just

this.setState(() => ({
  className: "wrapper_overlay"
}));
1

In React.js, running program thread does not wait for setting state and continues its execution, until and unless operation defined in setState() callback.

Your state is getting set but as your alert() is after setstate i.e. not in callback of setState() that's why its getting previous value because at the time state is setting new value, thread is not waiting but executing the next instruction which is alert().

if (this.props.overlay) {
    this.setState({ className: "wrapper_overlay" }, () => alert(this.state.className););
}

Hope this works for you.

1

Just use the callback method to update the state, as setState() might work asynchronously.

        this.setState(() => {
            className: "wrapper_clopsed"
        });

Not the answer you're looking for? Browse other questions tagged or ask your own question.