Sylar Sylar - 1 year ago 80
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?


this.state = {
checked: false
this._handleChange = this._handleChange.bind(this)

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


<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>

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

Edit for another method:

let checked = this.state.checked;
data: {"checked": checked },

Answer Source

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.

  this.setState({ checked: !this.state.checked }, () => {
    console.log(this.state.checked); // output will be as expected
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download