Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
How to chain a fetch API to a function then to another function?

I keep getting syntax error "Uncaught (in promise) ReferenceError: showQuestion is not defined" Trying to find ways to fix this problem. Also I'm still new to the whole thing.

fetch(
    'https://jservice.kenzie.academy/api/random-clue?valid=true'
)
    .then(response => response.json())
    .then(randomDataId => {
        const categoryDataId = randomDataId.categoryId;
        console.log(`category id is: ${categoryDataId}`);

        fetch(
            `https://jservice.kenzie.academy/api/clues?category=${categoryDataId}`
        )
            .then(response => response.json())
            .then(randomCatyId => {
                const rightAnswer =
                    randomCatyId.clues[randomData].answer;

                const showTitle =
                    randomCatyId.clues[randomData].category.title;

                const showQuestion =
                    randomCatyId.clues[randomData].question;

                showCategory.innerText = `Category: ${showTitle}`;

                h2Question.innerText = `Question: ${showQuestion}`;

                console.log('question: ' + showQuestion);
                console.log('answer: ' + rightAnswer);

                questionFetch();
            });
    });

function questionFetch() {
    h2Question.innerHTML = `Question: ${showQuestion}`;
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

fetch api is async in nature, and you are trying to read the data 'showQuestion' which is not yet available. please see the below code. use async-await, its much better way to play with fetch api.

 const randomData = 2; // fake Data

        async function GetDataFromApi(url) {
            const response = await fetch(url);

            return await response.json();
        }


        async function RunApp(params) {

            const randomDataId = await GetDataFromApi('https://jservice.kenzie.academy/api/random-clue?valid=true');

            const categoryDataId = randomDataId.categoryId;
            console.log(`category id is: ${categoryDataId}`);

            const randomCatyId = await GetDataFromApi(`https://jservice.kenzie.academy/api/clues?category=${categoryDataId}`);

            const rightAnswer = randomCatyId.clues[randomData].answer;
            const showTitle = randomCatyId.clues[randomData].category.title;
            const showQuestion = randomCatyId.clues[randomData].question;

            // showCategory.innerText = `Category: ${showTitle}`;

            // h2Question.innerText = `Question: ${showQuestion}`;

            console.log('question: ' + showQuestion);
            console.log('answer: ' + rightAnswer);

            questionFetch(showQuestion);
        }

        function questionFetch(showQuestion) {
            //h2Question.innerHTML = `Question: ${showQuestion}`;
        }

        RunApp();
about 4 years ago · Juan Pablo Isaza Relatório

0

The function questionFetch() does not have access to the showQuestion constant. This is because this constant is defined in the fetch request. The function showQuestion does not have access to data defined inside another function. (more on 'scope' here: https://www.w3schools.com/js/js_scope.asp)

To fix this, you should supply the constant showQuestion as an argument when calling the function questionFetch:

                questionFetch(showQuestion); //we supply the constant to the function
            });
    });

/**
     * function takes an argument, calls it x, and applies it as x. 
     * The name of the argument does not matter, 'x' just the label 
     * this function uses to hold the data supplied 
     * (in our case, the question string);
     * */
function questionFetch(x) { 
    h2Question.innerHTML = `Question: ${x}`;
}

Please make sure to define and supply the [randomData] argument used in the second fetch function, as it is currently undefined.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda