TypeError: Cannot read property '0' of undefined (Using MetaWeather API)

Hello! This is my first topic here. I am building an weather app in React that uses the MetaWeather API. Everything is fine until I try to send the property of an object inside of an array that’s on my state. This is what I mean:

constructor(props) {
        this.state = { 
        data: [
            consolidated_weather: [
                0: {air_pressure: value, 
                    the_temp: value,
                    // and many others}

When I try to render {this.state.data.consolidated_weather[0].the_temp}, I get the following error:


As you can see, I’m already checking if I have data before doing anything else. So, what could it be? I’ve really ran out of ideas to fix this :cold_sweat: I guess it’s something with the API request, but what?

I really appreciate any kind of help!

PS.: Sorry about my bad english, it’s not my first language :blush:

This is not a valid JavaScript I’m afraid and gives no clues about what might be a problem, can you provide actual code?

1 Like

Of course!

import React from 'react';
import axios from 'axios';

import './Home.scss';

import Current from '../UI/Current';
mport Card from '../UI/Card/Card';

class Home extends React.Component {

    constructor(props) {
        this.state = { 
            data: [],
            date: null,
            error: false

    componentDidMount() {
            .then(response => this.setState({data: response.data,   
                                            date: new Date().toDateString(), 
                                            temperature: Math.round(response.data.consolidated_weather[0].the_temp)}));

        return (
            <div className='container'> 
                <span> Today </span>
                <span> Tomorrow </span>
                {this.state.data ? 
                        <Current place={this.state.data.title} date={this.state.date} temperature={this.state.data.consolidated_weather[0].the_temp}/> 
                        <Card type='max_temp'/> 
                        <Card type='min_temp'/>
                : null}
export default Home;