Search code examples
javascriptapiasynchronousaxios

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 cant figure it out at all, basically everytime 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 isnt obvios, thank you.

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 seperate async functions, one to summon the new deck and one to pull from the deck with and that didnt work. also kept looking at the api website to see if im typing any of this wrong and it doesnt 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);