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

377
Visualizações
Trying to access JSON data throws error on first click, but works on second click

I'm building a simple app that accesses an API and renders out information. It's activated by an event listener in a button, which takes the value of the html input field and plugs it into my apiCall function. My code then processes the api response and assigns the desired data to a variable inside of an object, which is then console.log'ged out.

Here's my problem: when I click the button the first time, I get this error message:

Uncaught TypeError: Cannot read properties of undefined (reading 'average_price')
    at Object.getAveragePrice (index.js:17)
    at render (index.js:27)
    at HTMLButtonElement.<anonymous> (index.js:33)

Then I click the button for the second time, and I get the correct data in my console. What am I doing wrong? Below is my javascript.

let jsonResponse = ""
let collectionName = ""
let inputEl = document.getElementById("input-el")
let buttonEl = document.getElementById("button-el")


function callApi(collectionName) {
    fetch(`https://api.opensea.io/api/v1/collection/${collectionName}/stats`)
    .then(response => response.json())
    .then(response => jsonResponse = response)
    .catch(err => console.error(err));
}

const getJsonData = {
    getAveragePrice: function() {
        collectionData.averagePrice = jsonResponse.stats["average_price"]
    }
}

let collectionData = {
    averagePrice: ""
}

function render() {
    callApi(collectionName)
    getJsonData.getAveragePrice()
    console.log(JSON.stringify(collectionData.averagePrice))
}

buttonEl.addEventListener("click", () => {
    collectionName = inputEl.value
    render()
})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I se a couple of issues on your code, the one that you are encountering is:

First, It's because the initial value of jsonResponse is a string and you are accessing it as an object.

let jsonResponse = ""

yet you're accessing it as:

jsonResponse.stats["average_price"]

Changing the default value to this will fix the error:

let jsonResponse = {
  stats: {
    average_price: 0
  }
}

HOWEVER, this will "not fix" your logic, because what you are expecting is that the callApi has finished calling before the getJsonData.getAveragePrice() will be triggered.

That is the second issue where you need to either use async/await or promise to fulfill this.

I added some comments on the code improvements:

function callApi(collectionName) {
    // return the promise
    return fetch(`https://api.opensea.io/api/v1/collection/${collectionName}/stats`)
    .then(response => response.json())
    .then(response => jsonResponse = response)
    .catch(err => console.error(err));
}

// make this function async
async function render() {
    // add await on call API so it will finish the promise first
    await callApi(collectionName)
    getJsonData.getAveragePrice()
    console.log(JSON.stringify(collectionData.averagePrice))
}

buttonEl.addEventListener("click", async () => {
    collectionName = inputEl.value
    await render()
})
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