Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

365
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!