简体   繁体   中英

Access an object inside another object returns cannot read property of undefined

I have a trivial problem but I can't solve for some reason.

I have an object, which is a return request from an API:

state = { 
        data: []
    }

    componentDidMount() {
        fetch(`https://api.openweathermap.org/data/2.5/weather?q=Toronto,CA&appid=${appkey}`)
        .then(data => data.json())
        // .then((data) => {
        //  console.log(data);
        // })
        .then(data => this.setState({data}))

    }

and:

render() {
const weather = this.state.data
console.log(weather.main);

The first part is what comes first before the react component. I was able to fetch an object and then I create a variable (const) which return another object, in this case:

{feels_like: 271.85
temp_min: 272.15
temp_max: 276.48
pressure: 1027
humidity: 97}

For my ignorance, the weird part is that, if I try to access for example the first value (feels_like) in this way:

weather.main.feels_like

it will throw an error which is Cannot read property 'feels_like' of undefined.

Now, I tried to loop through the object but it didn't work and I tried to access the property with a different syntax but still, it threw an error.

Am I missing something?

The goal is to create a component like that:

console.log(this.state.data);
 const weather = this.state.data;
 return (

  <div>
  <div key={weather.id}>
  <h3>Library Product of the Week!</h3>
  <h4>{weather.name}</h4>
  <h4>{weather.main.temp}</h4>
  <h4>{weather.main.feels_like}</h4>
  <h4>{weather.main.temp_min}</h4>
  <h4>{weather.main.temp_max}</h4>
  <h4>{weather.main.pressure}</h4>
  <h4>{weather.main.humidity}</h4>
  </div>
  </div>
  )
}

That's the entire code:

import React from 'react'
 import { render } from 'react-dom'

 const appkey = 'xx';

 class Message extends React.Component {

    state = { 
        data: []
    }

    componentDidMount() {
        fetch(`https://api.openweathermap.org/data/2.5/weather?q=Toronto,CA&appid=${appkey}`)
        .then(data => data.json())
        // .then((data) => {
            //  console.log(data);
            // })
            .then(data => this.setState({data}))

        }

        componentDidUpdate() {
            console.log("The component just updated")
        }

        render() {
            console.log(this.state.data);
            const weather = this.state.data;
            return (

                <div>
                <div key={weather.id}>
                <h3>Library Product of the Week!</h3>
                <h4>{weather.name}</h4>
                <h4>{weather.main.temp}</h4>
                <h4>{weather.main.feels_like}</h4>
                <h4>{weather.main.temp_min}</h4>
                <h4>{weather.main.temp_max}</h4>
                <h4>{weather.main.pressure}</h4>
                <h4>{weather.main.humidity}</h4>
                </div>
                </div>
                )
        }
    }

    render(
        <Message />, 
        document.getElementById('root')
        )

From the code you provided it seems that you're already accessing the data before it has been saved to the state for the first time. So you're trying to get the feels_like value from your empty array which is your initial state.

In order to fix it you should check if your data is present before using it in your render method

EDIT:

For some reason the API key didn't work for me and the docs mentioned it could take a few hours before it will work so I won't be able to test that for you. But the code sandbo x checks if the data is present before rendering it. And it will render some text if the data is uninitialized. Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM