function Blackjack() {
const [deck, setDeck] = useState([]);
const [playerHand, setPlayerHand] = useState([]);
const [dealerHand, setDealerHand] = useState([]);
function resetDeck() {
const suits = ["S", "H", "C", "D"];
const values = [
"A",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"J",
"Q",
"K",
];
let newDeck = [];
for (let s of suits) {
for (let v of values) {
newDeck.push(v + s);
}
}
setDeck(newDeck);
return newDeck;
}
function deal() {
let curDeck = resetDeck();
let player = [];
let dealer = [];
for (let i = 0; i < 4; i++) {
let randIndex = Math.trunc(Math.random() * curDeck.length);
let card = curDeck[randIndex];
curDeck.splice(randIndex, 1);
if (i < 2) player.push(card);
else dealer.push(card);
}
setPlayerHand(player);
setDealerHand(dealer);
setDeck(curDeck);
}
function hit() {
let curDeck = deck;
let curPlayerHand = playerHand;
let randIndex = Math.trunc(Math.random() * curDeck.length);
let card = curDeck[randIndex];
curDeck.splice(randIndex, 1);
curPlayerHand.push(card);
setDeck(curDeck);
setPlayerHand(curPlayerHand);
}
return (
<div>
<div>{dealerHand}</div>
<button onClick={deal}>Deal</button>
<button onClick={hit}>Hit</button>
<button>Stand</button>
<div>{playerHand}</div>
</div>
);
}
export default Blackjack;
I am trying to learn how to use React and I have come across a strange issue when using the useState()
hook. When I click the deal
button it renders the dealerHand
and playerHand
properly. However when I click the hit
button nothing changes. The state does appear to change after some time when I inspect the components in the console, however it is very slow. Even after the state is changed, the displayed values still remain the same. What am I missing?