pdrake1988
pdrake1988

Reputation: 43

state won't update inside react function component

I'm building a Blackjack game in React.js. And I have set the state to an array of type cards. It looks like this.

    let startingDealerHand: Cards[] = dealCards(2, []);
    let startingPlayerHand: Cards[] = dealCards(2, []);
    const [dealerHand, setDealerHand] = useState<Array<Cards>>(startingDealerHand);
    const [playerHand, setPlayerHand] = useState<Array<Cards>>(startingPlayerHand);

I'm trying to update the state inside of an onclick function that looks like this.

takeHit={(hand: Cards[]) => setPlayerHand(dealCards(1, hand))}

I tried debugging the application and onClick is doing what it is supposed to do, however the ui as well as the state isn't updating for some reason.

Upvotes: 1

Views: 52

Answers (1)

cssyphus
cssyphus

Reputation: 40038

Try:

onClick={(hand: Cards[]) => setPlayerHand(dealCards(1, hand))}

or:

onClick={() => handleTakeHit(hand)}

and above, just under where your useState consts are created, add:

const handleTakeHit = (hand:Cards[]) => {
    setPlayerHand(dealCards(1, hand) )
}

Upvotes: 1

Related Questions