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

192
Views
Type Error 'Can't read properties of undefined' - Accessing API in React

Building a Weather app in React JS using OpenWeatherMapAPI. What I am trying to do is render dynamic backgrounds based on the response of the API.

The end point for the data I'm looking for is 'data.weather[0].main' and it will show the text 'Clear', 'Cloudy', 'Rain', etc... I will then pass the value through as a prop to my styled component to render the corresponding image. This is where I am getting the error: TypeError: Cannot read properties of undefined (reading '0').

I know this is because it is a nested child in the JSON doc. All the first levels work such as "data.main" or "data.timezone".

I have tried the following and still get the same error:

console.log(data?.weather[0] ? data.weather[0].main : '')

const Weather = ({data}) => {

    // Error here
    console.log(data?.weather[0] ? data.weather[0].main : '')
    
    return (

        // Error here
        <StyledContainer bg={data.weather[0].main}>
            <Title>Style me</Title>
            <Heading>{data.name}</Heading>
        </StyledContainer>
    )
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Optional chaining can be used on arrays too...

console.log(data?.weather?.[0].main ?? "")
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!