I have this function in my .tsx file:
doIsChecked() {
var isItChecked = document.getElementById('isPless') as HTMLInputElement;
console.log('updateDocsFlag before: ' + this.state.updateDocsFlag);
if (isItChecked.checked) {
this.setState({ updateDocsFlag: true });
} else {
this.setState({ updateDocsFlag: false });
}
console.log('updateDocsFlag after: ' + this.state.updateDocsFlag);
}
It get called when a checkbox is ticked/unticked. I noticed that if isItChecked is true updateDocsFlag is false as can be seen in the before and after log entries. This isn't the behaviour I expected Is there something wrong with my code?
this.setState is asynchronius. it does set the right state,but not at the moment of the call. so when you call
console.log('updateDocsFlag after: ' + this.state.updateDocsFlag);
you still see the old state. try to do following:
doIsChecked() {
var isItChecked = document.getElementById('isPless') as HTMLInputElement;
console.log('updateDocsFlag before: ' + this.state.updateDocsFlag);
let updateDocsFlag = isItChecked.checked;
this.setState({ updateDocsFlag });
console.log('updateDocsFlag after: ' + updateDocsFlag);
}
this way you log not the state, but the value you passing into the state. You suppose to see there the right value. (and the actual state will update with this value after all active functions traces will end)