Reputation: 15665
I have the following method in a react component:
handleCheckBoxClick() {
var checkbox = document.getElementById("boldCheckbox").checked;
this.setState({ischecked : checkbox});
if(this.state.ischecked) {
this.setState({weight:'bold'});
} else {
this.setState({weight:'normal'});
}
}
but if I change the if statement to:
if(checkbox) {
this.setState({weight:'bold'});
} else {
this.setState({weight:'normal'});
}
it works fine but I can't figure out why the first way doesn't work.
Upvotes: 1
Views: 3262
Reputation: 89
Thats cause this.setState({ isChecked : checkbox });
has not finished before you ask it in the if statement.
Upvotes: 0
Reputation: 191976
The method setState()
is asynchronous, and updates are often batched together. In your case, ischecked
is updated together with the weight
, so when you set the weight
you still refer to the old value.
One solution is to use setState()
's callback that will be called after the state is updated.
Note: to get the checkbox checked
state, use the event object e
passed to the handler instead of querying the DOM.
handleCheckBoxClick(e){
var checked = e.target.checked;
this.setState({ischecked : checked}, function() {
if(this.state.ischecked){
this.setState({weight:'bold'});
}else{
this.setState({weight:'normal'});
}
});
}
A better solution is to update both properties because you know if the checkbox is checked:
handleCheckBoxClick(e){
var checked = e.target.checked;
this.setState({
ischecked : checked,
weight: checked ? 'bold' : 'normal'
});
}
Upvotes: 3