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

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

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 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