0

I have a function called drawCard, which fetch card from API, then change state of counter depending of the card. I run it in useEffect 4 times. I have this counter displayed in html, and it shows correct value, but when I log the value of counter, it always gives me 0 (initial). However, when I use it on button, everything works properly.

Why it doesn's see value when ran on useEffect? I need it to check which value assign to ace card (11 or 1).

TheGame.js (part)

const [playerCounter, setPlayerCounter] = useState(0);
const [secondPlayerCounter, setSecondPlayerCounter] = useState(0);
const [croupierCounter, setCroupierCounter] = useState(0);
const [temporaryCount, setTemporaryCount] = useState(0);

useEffect(() => {
    const dealCards = async () => {
        await drawCard(setPlayerHand, playerCounter, setPlayerCounter, deck);
        console.log(playerCounter);
        await wait();
        await drawCard(setPlayerHand, playerCounter, setPlayerCounter, deck);
        console.log(playerCounter);
        await wait();
        await drawCard(setCroupierHand, temporaryCount, setTemporaryCount, deck, temporaryCount);
        await wait();
        await drawCard(setCroupierHand, croupierCounter, setCroupierCounter, deck, temporaryCount);
        console.log(playerCounter);
        console.log(croupierCounter);
    }
    if(isStarted) {
         dealCards();
    }
}, [isStarted]);

const onHitHandler = () => {                 // works fine 
        drawCard(setPlayerHand, playerCounter, setPlayerCounter, deck)
};

DrawCard.js

import {fetchCard} from '../components/Game/Fetch.js';

export const drawCard = async (handSetter, count, countSetter, deck, temporaryCount = 0) => {
    let card = await fetchCard(deck, 1);
    handSetter((oldHand) => [...oldHand, card])
    console.log(count);
    if (card[0].value === 'ACE') {
        if(count + temporaryCount + 11 <= 21) {
            countSetter(prevCount => prevCount + 11);
        }
        else {
            countSetter(prevCount => prevCount + 1);
        }
    }
    else if (card[0].value === 'JACK' || card[0].value === 'QUEEN' || card[0].value === 'KING') {
        countSetter(prevCount => prevCount + 10);
    }
    else {
        countSetter(prevCount => prevCount + Number(card[0].value));
    };
}
szemeg
  • 51
  • 1
  • 7
  • "*when I log the value of counter, it always gives me 0 (initial)*" - where and how are you logging it? I can't see that in your code – Bergi Jul 28 '22 at 13:02
  • @Bergi sorry, fixed that. but those are example, tried multiple places. I need to access current count in `drawCard` function, in this `useEffect` – szemeg Jul 28 '22 at 13:11
  • It's because you do log the `const`ant from the time when the effect triggered. If you did log the `prevCount` instead, it would work. – Bergi Jul 28 '22 at 13:16

0 Answers0