React TypeError: this.state.object.array[0] is undefined

Viewed 34

I'm making a weather app in React and I'm having problems accessing an array inside an object in state. Here is my code:

import React from 'react';

export default class CurrentWeather extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            weatherData: {},
        };
    }

    componentDidMount() {
        fetch("https://api.openweathermap.org/data/2.5/weather?q=City&appid=ID&units=metric")
            .then(res => res.json())
            .then(
                (weatherData) => {
                    return this.setState({
                        weatherData: weatherData,
                    });
                },
            )
    }

    render() {
        const getWeather = this.state.weatherData;
        return (
            <div>
                <p>{ JSON.stringify(getWeather.weather) }</p>
                { /* [{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}] */}

                <p>{ JSON.stringify(getWeather.weather[0]) }</p>
                { /* TypeError: getWeather.weather is undefined */}
            </div>
        );
    }
}

I've commented with what happens, and I cannot figure out why this is happening. Below is what this.state.weatherData.weather contains:

    "weather": [
        {
            "id": 600,
            "main": "Snow",
            "description": "light snow",
            "icon": "13n"
        }
    ]

1 Answers

You have to define weatherData in Contrast by typing an array

import React from 'react';

export default class CurrentWeather extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            weatherData: [],
        };
    }

    componentDidMount() {
        fetch("https://api.openweathermap.org/data/2.5/weather?q=City&appid=ID&units=metric")
            .then(res => res.json())
            .then(
                (weatherData) => {
                    return this.setState({
                        weatherData: weatherData,
                    });
                },
            )
    }

    render() {
        const getWeather = this.state.weatherData;
        return (
            <div>
                <p>{ JSON.stringify(getWeather.weather) }</p>
                { /* [{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}] */}

                <p>{ JSON.stringify(getWeather ?getWeather.weather[0] :'') }</p>
                { /* TypeError: getWeather.weather is undefined */}
            </div>
        );
    }
}
Related