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

191
Vistas
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 Respuestas
Responde la pregunta

0

Optional chaining can be used on arrays too...

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