1

I have a React class with this constructor:

class AddList extends Component {
constructor(props){
  super(props);
  this.state = { hidden: true };
}

Then I have this function:

handleSubmit(e) {
e.preventDefault(); // this prevents the page from reloading -- do not     delete this line!

// Implement the rest of this function here!
alert('this.state.hidden: ' + this.state.hidden);
if (this.state.hidden == true){
  alert('setting hidden to false');
  this.setState({hidden: false});
  }
  else{
    alert('setting hidden to true');
    this.setState({hidden: true});
  }
alert('this.state.hidden: ' + this.state.hidden);
    . . . 

My problem is that neither this.setState({hidden: false);
nor                        this.setState({hidden: 'false'); 

Changes the state! The 'alert' boxes confirm the path through the code and ONLY 'setState' seems to be a NOP!

Jim Kay
  • 91
  • 6

2 Answers2

2

setState is asynchronous and therefore you won't be able to see the updates afterwards. That's why you don't see the up to date value on your last alert call.

For more information check ReactJs's doc: https://facebook.github.io/react/docs/state-and-lifecycle.html#using-state-correctly

I wrote a sample code based on yours:

class AddList extends React.Component {
  constructor(props) {
    super(props)
    
    this.state = { hidden: true }
    
    this.handleSubmit = this.handleSubmit.bind(this)
  }
  
  handleSubmit(event) {
    event.preventDefault()
    
    this.setState({ hidden: !this.state.hidden })
  }
  
  render() {
    return (
      <div>
        <div>State value: {this.state.hidden ? 'hidden' : 'visible'}</div>
        <button onClick={this.handleSubmit}>Click-me</button>
      </div>
    )
  }
 }
 
 ReactDOM.render(<AddList />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>
Hemerson Carlin
  • 7,354
  • 1
  • 27
  • 38
2

In case if you want to read the state values after updating it, you can use the second argument of setState method which is a callback function. This callback function executes after the state is updated and component is re-rendered. For ex. this.setState({ hidden: !this.state.hidden }, function(){ console.log("updated state: " + this.state.hidden); });

Ishan Trivid
  • 101
  • 3