0

I have a simple react component:

export default class RidiculousCheckbox extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isChecked: true,
        };
    }

    handleInputChange(event) {
        window.console.log("Value of event:" + event.target.checked);
        this.setState({isChecked: event.target.checked});
        window.console.log("State after setting, is checked:" + this.state.isChecked);
    }

    render() {
        return (
            <form>
                <input
                    type="checkbox"
                    checked={this.state.isChecked}
                    onChange={this.handleInputChange.bind(this)}/>
            </form>
        );
    }
}

When I display it for the first time the box is checked. Then I click on it, the box unchecks

Value of event:false
State after setting:true

If i click it again, the check box comes back, and the output:

Value of event:true
State after setting:false

Why is the state being set to true in the first example, when the value of event.target.checked is clearly false?

Ryan
  • 782
  • 1
  • 10
  • 25

2 Answers2

3

It's because setState function is asynchronous and when you're checking for new value "State after setting:true" - its just didn't change yet.

If you want to look on state after setState, use callback:

this.setState({...}, () => {
  window.console.log("State after setting, is checked:" + this.state.isChecked);
})
0

Replace

this.setState({isChecked: event.target.checked});

By

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

And everything should work fine since you are toggling the value.

Or more readable :

this.setState((previousState) => ({ isChecked: !previousState.isChecked }));
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254