1

I am new in React.js. I have below code, where the variable modalOpen value is not changing.

constructor(props) {
    super(props);

    this.state = {
      modalOpen: false,
    };

    this.view = this.view.bind(this);
}
view() {
    this.setState({ modalOpen: true });

    alert(this.state.modalOpen)
}
render() {
    return (
        <button className="mini ui button" onClick={this.view}>
            <i className="user icon"></i>
            View
        </button>
    )
}

How can I change the value ?

abu abu
  • 6,599
  • 19
  • 74
  • 131
  • 1
    It is changing, just not right after you call it. `this.setState` doesn't update the state immediately. [See this question for more details.](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) – kingdaro Apr 26 '18 at 03:08

3 Answers3

3

Your code is correct you may need to put the alert in call back of setState or in render

  constructor(props) {
    super(props);

    this.state = {
      modalOpen: false,
    };

    this.view = this.view.bind(this);
  }
  view() {
    this.setState({ modalOpen: true }, ()=>{
      alert(this.state.modalOpen)
    });

  }
  render() {
    return (
      <div>
      <button className="mini ui button" onClick={this.view}>
        <i className="user icon"></i>
        View
        </button>
      {this.state.modalOpen ? 'true' : 'false'}
        </div>
    )
  }
}
Liam
  • 6,517
  • 7
  • 25
  • 47
1

from React Docs:

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

setState(updater, callback)

A. If you want to do something with the prev state, you'd better pass a function as a updater to setState.

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

B. For your case, after updating the state and want to call the callback function, you will need the callback for the setState, for example:

view() {
  this.setState({
    modalOpen: true
  }, () => {
    alert(this.state.modalOpen)
  });
}
Yuying Wu
  • 136
  • 5
1

Because setState is asynchronous。 The reason react does that is to improve performance. It's like when you add a listener to window.resize event, you don't want your listener to be called every time resize event is emitted.

Chef
  • 633
  • 5
  • 17