fireclint
fireclint

Reputation: 65

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

Upvotes: 1

Views: 107

Answers (1)

Phil
Phil

Reputation: 164785

Optional chaining can be used on arrays too...

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

Upvotes: 1

Related Questions