Created
December 30, 2022 22:37
-
-
Save kivircik-parantez/566d40cb3ecf6a33de6645fc16c1bbd6 to your computer and use it in GitHub Desktop.
Chains of Computation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Game() { | |
const [card, setCard] = useState(null); | |
const [goldCardCount, setGoldCardCount] = useState(0); | |
const [round, setRound] = useState(1); | |
// ✅ Calculate what you can during rendering | |
const isGameOver = round > 5; | |
function handlePlaceCard(nextCard) { | |
if (isGameOver) { | |
throw Error('Game already ended.'); | |
} | |
// ✅ Calculate all the next state in the event handler | |
setCard(nextCard); | |
if (nextCard.gold) { | |
if (goldCardCount <= 3) { | |
setGoldCardCount(goldCardCount + 1); | |
} else { | |
setGoldCardCount(0); | |
setRound(round + 1); | |
if (round === 5) { | |
alert('Good game!'); | |
} | |
} | |
} | |
} | |
// ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment