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?

2

2 Answers 2

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);
})
Sign up to request clarification or add additional context in comments.

Comments

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 }));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.