Estoy creando una aplicación simple que accede a una API y muestra información. Se activa mediante un detector de eventos en un botón, que toma el valor del campo de entrada html y lo conecta a mi función apiCall . Luego, mi código procesa la respuesta de la API y asigna los datos deseados a una variable dentro de un objeto, que luego se desconecta de la consola.
Este es mi problema: cuando hago clic en el botón por primera vez, aparece este mensaje de error:
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)Luego hago clic en el botón por segunda vez y obtengo los datos correctos en mi consola. ¿Qué estoy haciendo mal? A continuación se muestra mi 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() })Veo un par de problemas en su código, el que está encontrando es:
Primero, es porque el valor inicial de jsonResponse es una cadena y está accediendo a él como un objeto.
let jsonResponse = ""sin embargo, estás accediendo a él como:
jsonResponse.stats["average_price"]Cambiar el valor predeterminado a esto solucionará el error:
let jsonResponse = { stats: { average_price: 0 } } SIN EMBARGO, esto "no arreglará" su lógica, porque lo que espera es que callApi haya terminado de llamar antes de que se getJsonData.getAveragePrice() .
Ese es el segundo problema en el que debe usar async/await o prometer cumplir con esto.
Agregué algunos comentarios sobre las mejoras del código:
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() })