javascriptasynchronousaxios

deckOfCards API wont choose card from the deck with the specific deck ID


I have been stuck on this for so long and the answer is probably so simple but I can't figure it out at all, basically every time I click the button to draw a card its giving me a brand new deck and not using the deck with the same ID as the one I am trying to draw from. I am new if it isn't obvious,

let deckOfCardsApi = 'https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1'
const button = document.querySelector('#giveCardButton');

const drawCard = async () => {
    try {
        const response = await axios.get(deckOfCardsApi);
        let deckId = response.data.deck_id;
        const drawCard = await axios.get(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=1`)
        console.log(deckId);
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};
button.addEventListener('click', drawCard);

I tried making two separate async functions, one to summon the new deck and one to pull from the deck with and that didn't work. I also kept looking at the API web site to see if I'm typing any of this wrong and it doesn't seem like it.


Solution

  • When you click on the button drawcard deckOfCardsApi function is called everytime which gives you new deck everytime, which is the reason you get card from brand new deck.

    Simple Solution

    // API endpoint for creating a new shuffled deck
    const deckOfCardsApi = 'https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1';
    const button = document.querySelector('#giveCardButton');
    
    let deckId;
    
    const drawCard = async () => {
        try {
            if (!deckId) {
                // If we don't have a deck ID, create a new deck
                const response = await axios.get(deckOfCardsApi);
                deckId = response.data.deck_id;
                console.log('New deck created with ID:', deckId);
            }
            
            // Draw a card from the deck
            const drawResponse = await axios.get(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=1`);
        } catch (error) {
            console.error('Error:', error.message);
        }
    };
    
    button.addEventListener('click', drawCard);