React useState hook updating inconsistently
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?
1 answer
-
answered 2022-01-23 02:20
KyleRifqi
I was having your same issue a few days ago but it worked by doing this:
// change this setState(state) // to this setState([ ...state ]) setState({ ...state })
the state checks if the objects are the same, so you have to use the spread operator to make a new object.
How many English words
do you know?
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
how many words do you know
Powered by Examplum