Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda