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()
})
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