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

214
Vistas
Click button only once (opensea collection stats api)

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

The fetch call is asynchronous. This means that in your render function, when callApi returns, the request hasn't completed yet. So the rest of render will be working with undefined values until the fetch completes - by the time you've clicked the button a second time, the first fetch has probably finished, which is why it then works.

At the moment your program flow is

event listener -> render -> callApi -> (fill in response data)

meaning that the first time, render has no response data to work with, but on the second button press, render has got the response data from the first run.

So you need to remove callApi() from render(), and call callApi() from the event listener instead of calling render(); then, change callApi() so that it calls render() when the fetch() promise is fulfilled.

The program flow will then be

event listener -> callApi -> fetch -> (fill in response data) -> 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