I want to change CSS class of body when user clicks a button, and reverse that when operations defined in handleClick are finished.
I have following handleClick function:
handleClick = data => {
document.body.classList.add('waiting');
this.setState({data}, () => document.body.classList.remove('waiting'));
}
I would expect that to work in following way:
- Add
waitingclass to body - Change state of component
- Remove
waitingclass from body
But it doesn't work that way. In order for that to work I have to change handleClick function to something like this:
handleClick = data => {
document.body.classList.add('waiting');
setTimeout(() => this.setState({data}, () => document.body.classList.remove('waiting')))
}
I would like to know why this works.
I know that setTimeout is 'delaying' execution of this.setState but as far as I know this.setState itself is asynchronous so shouldn't it be delayed on its own? Does that mean that changing document.body.classList is also asynchronous and its execution is delayed more than execution of this.setState?