In this coin flipping program, there is a delay in the updated state.flipResult and state.coinURL variables being printed to console (they are always a click behind what is shown in the UI).
I'm sure it has something to do with setState updates being asynchronous. How then, can I "force" a state update and rerender?
I've seen examples of passing prevState to the setState function in order to force an update to a counter, for instance, but in this instance the flipResult and coinURL ( both "heads" or "tails") are not based on the previous state. I could find a way to toggle between heads and tails using prevState, but I might also want, in future, to "force" an instant state update based on a user's input or selection, unrelated to previous state. Is there a way to do this?
Many thanks in advance for any help!
Here's the code:
import React, { Component } from "react";
import "./styles.css";
class App extends Component {
state = {
flipResult: "",
coinURL: ""
};
flipCoin = () => {
let number = Math.floor(Math.random() * 100) + 1;
if (number <= 50) {
this.setState( { flipResult: "heads", coinURL: "heads" });
} else if (number >= 51) {
this.setState({ flipResult: "tails", coinURL: "tails" });
}
console.log("flipResult is " + this.state.flipResult);
console.log("flipResult is " + this.state.coinURL);
};
render() {
return (
<div>
<h2> Flip a coin! </h2>
<br />
<button onClick={this.flipCoin}> Flip! </button>
<br />
{this.state.flipResult ? (
<div>
The result is {this.state.flipResult}.
<br />
<br />
<img
src={`./img/${this.state.coinURL}.jpg`}
alt="coin"
style={{ width: "200px", height: "auto" }}
/>
</div>
) : (
<div> No result yet! </div>
)}
</div>
);
}
}
export default App;
Web app can be found here - https://codesandbox.io/s/flipcoin-zj9sl?file=/src/App.js