0
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?

JJBeaudry
  • 33
  • 5
  • If I have `const [arr, setArr] = useState([1, 2, 3, 4, 5, 6, 7]);` I should use `setArr([...arr.slice(0, 3), ...arr.slice(5)])` and not `arr.splice(3, 2)` – keemahs Jan 23 '22 at 02:34
  • 1
    Example in your code, inside the `hit` function, you are doing `let curDeck = deck;` then `curDeck.splice(randIndex, 1);` and then `setDeck(curDeck);` which is not the right way – keemahs Jan 23 '22 at 02:35

1 Answers1

-1

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.

KyleRifqi
  • 489
  • 2
  • 15