Sylar Sylar - 2 months ago 17
Javascript Question

Cannot get correct state of checkbox

Something weird is happening. Im using foundation switch as my checkbox.

When I look at my state on the react browser tool, my check state is true. When I console log the state in the handler, it's false. Where is the bug?

es6:

constructor(props){
super(props);
this.state = {
checked: false
},
this._handleChange = this._handleChange.bind(this)
}

_handleChange(){
this.setState({ checked: !this.state.checked });
console.log(this.state.checked); // becomes the opposite the state!
}


render:

<div className="switch">
<input className="switch-input" id="exampleSwitch" type="checkbox" onChange={this._handleChange} checked={this.state.checked} name="exampleSwitch">
<label className="switch-paddle" htmlFor="exampleSwitch">
<span className="show-for-sr">Download Kittens</span>
</label>
</div>


When clicked, my react console shows it as
true
but in console, it's
false
. The
console.log()
shows the opposite of the state. If the state is
false
then the log shows
true
. Any reason?

Edit for another method:

_onSubmit(){
let checked = this.state.checked;
$.ajax({
...
data: {"checked": checked },
...
});
}

Answer

From React documentation:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

So console.log() may work in unexpected manner here. To get proper result you probably would like to pass 2nd argument to your setState():

The second (optional) parameter is a callback function that will be executed once setState is completed and the component is re-rendered.

_handleChange(){
  this.setState({ checked: !this.state.checked }, () => {
    console.log(this.state.checked); // output will be as expected
  });  
}
Comments