Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
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 Respostas
Responde à pergunta

0

Optional chaining can be used on arrays too...

console.log(data?.weather?.[0].main ?? "")
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda