Skip to content Skip to sidebar Skip to footer

Reactjs State Not Updating

constructor(props) { super(props); this.state = { active: false, showSideBar: false, className: '' } } componentDidMount() { if (this.props

Solution 1:

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

Solution 2:

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);});
   }

Solution 3:

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.

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

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

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

or just

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

Solution 4:

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.

Solution 5:

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

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

Post a Comment for "Reactjs State Not Updating"