After coming back from Vue land I find myself suddenly back in React land and my usage of hooks so far haven’t gotten passed the basic stages until today where I found myself trying to update multiple states when the depecendy mapped for useEffect changes
So basically my thought was to implement a Blackjack hook, for starters it will just be client side and that might be putting me into some problems I shouldn’t face if I had the backend done. But I still want to learn what I can do to avoid this in the future my hook has these functions:
const drawDealerCard = useCallback(() => {
console.log("drawDealerCard");
setDeck((prevDeck) => {
const deckCopy = [...prevDeck];
const newCard = deckCopy.pop();
console.log("setDeck");
setDealerHand((prevHand) => {
console.log("setDealerHand");
return [...prevHand, newCard!];
});
return deckCopy;
});
}, []);
useEffect(() => {
if (!isDealerHidden) {
console.log("useEffect isDealerHidden changed");
drawDealerCard();
}
}, [isDealerHidden, drawDealerCard]);
When isDealerHidden
changes to false
I want to call the drawDealerCard
function. I put it outside because I have this useEffect that deals a new card when the dealer hasn’t reached a high enough score
if (!isDealerHidden && dealerHand.length >= 2) {
const dealerScore = calculateScore(dealerHand as PlayingCard[]);
console.log("Dealer hand", dealerHand);
console.log("Dealer score", dealerScore);
setDealerScore(dealerScore);
if (parseInt(dealerScore) < 17) {
setTimeout(() => {
//drawDealerCard();
}, 1000);
}
}
}, [dealerHand, isDealerHidden, drawDealerCard]);
I have not come to any errors with this yet.
But my problem is from the first code that the “setDeck” state update is running twice, as i get double the console output and the setDealerHand in turn is logged 4 times. How do I avoid this as this would give the “Dealer” 3 cards with the new card duplicated and not the expected 2.