When the coin is on HEADS and the logic runs and determines that its HEADS again on the next flip the animation will not trigger because its dependent on a className changing and then having CSS take care of the animation. We are using state to change the className. I figured that setting the state to be null or something would work because technically the className is changing but maybe it runs to fast for the browser to notice? Order of code should be: Flip Logic, JSX ClassName that changes, CSS for animation
const flipCoin = () => {
setCoin("");
const random = Math.random();
if (random < 0.5) {
console.log(random);
setCoin("heads");
setHeadsCount(headsCount + 1);
} else {
console.log(random);
setCoin("tails");
setTailsCount(tailsCount + 1);
}
};
<div className="coinContainer">
<div id="coin" className={`animate-${coin}`}>
<div id="heads" className="heads"></div>
<div id="tails" className="tails"></div>
</div>
</div>
.animate-heads {
animation: flipHeads 3s;
animation-fill-mode: forwards;
}
@keyframes flipHeads {
from {
transform: rotateY(0deg);
}
to {
transform: rotateY(1800deg);
}
}
.tails {
background-image: url(./assets/tails.jpg);
transform: rotateY(-180deg);
}
.animate-tails {
animation: flipTails 3s;
animation-fill-mode: forwards;
}
SO if anyone has an answer that would be amazing. Thank you for your time.
I'm assuming that your flipCoin() method is called within a React event handler. State changes are "batched" within in event handler, which is to say a setState will enqueue a change in state, but won't trigger a render until the event handler returns, and will only factor in the last setState (See this article).
In order to ensure that the event handler returns before your second setState that sets heads or tails, you can wrap it in a setTimeout(...,0):
setTimeout(() => {
setCoin("heads") // or tails
}, 0);
You may also want to consider using setImmediate and/or its browser polyfill (see this library), which basically ensures that its callback will be run as soon as possible after the event queue is flushed (read more here).