Binaromong
Binaromong

Reputation: 572

React checkbox toggle: behaviour is opposite to that expected

I'm making a simple react component that is supposed to track the state of a checkbox within a table row.

class EventRowAdmin extends Component {
constructor(props) {
    super(props);
    this.state = { isChecked: false };
    this.handleChange = this.handleChange.bind(this);
}

handleChange(event) {
    this.setState(({ isChecked }) => (
      {
        isChecked: !isChecked
      }
    ));

    console.log(this.state.isChecked);
}

render() {
    return (
            <tr id={this.props.id}>
                <td><input onChange={this.handleChange} className="remove-event" type="checkbox" /></td>
            </tr>
    )
    }
}

As you can see from the code, I'm logging the current state of the checkbox to the console once the checkbox has been clicked.

Although the initial state is set to false, clicking on the checkbox causes "false" to be outputted to the console once it is clicked. Once it is clicked again (unchecked), "true" is outputted to the console.

Any explanation for this?

Upvotes: 0

Views: 2027

Answers (1)

Johnson Samuel
Johnson Samuel

Reputation: 2076

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. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

If you want to see the updated state value after setState, use the optional callback parameter:

     handleChange(event) {
        this.setState(({ isChecked }) => (
          {
            isChecked: !isChecked
          }
        ), function () {
            console.log(this.state.isChecked, 'updated state value');
        });
        console.log(event.target.checked);
      }

Here you can see the last console.log shows the actual value of the checkbox too..

Upvotes: 1

Related Questions