DEV Community

Undefined Nested Object in REST API with React Hooks?

mitchelln11 on June 04, 2020

Having trouble trying to access nested objects in the OpenWeather REST API. Getting full results in Postman, but not when trying to render. Postma...
Collapse
 
suelopoder profile image
Diego Sisto

It's most likely something silly. Try console.log(openWeather, openWeather.weather, openWeather.weather[0])

Collapse
 
mitchelln11 profile image
mitchelln11

comes back undefined.

Collapse
 
suelopoder profile image
Diego Sisto

You should have 3 outputs. Is that undefined, undefined, undefined?
Can we get the full code?

Thread Thread
 
mitchelln11 profile image
mitchelln11

Unhandled Rejection (TypeError): Cannot read property '0' of undefined. Breaks the page, doesn't even log anything.

Thread Thread
 
suelopoder profile image
Diego Sisto

Can we see the code please? It could be a number of things.

Thread Thread
 
mitchelln11 profile image
mitchelln11

It is in React and uses hooks.

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const LocalWeather = () => {
    const [openWeather, setWeather] = useState([]);

    useEffect(() => {
        axiosGet();
    }, []); //  Run once on load

    const axiosGet = () => {
        const data = axios.get(`https://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=${process.env.REACT_APP_WEATHER_KEY}`)
        .then(data => setWeather(data.data));
    console.log(openWeather, openWeather.weather, openWeather.weather[0]);
    }

    return (
        <ul>
            <li>{openWeather.name}</li>
            <li>{openWeather.cod}</li>
            <li>{openWeather.id}</li>
            <li>{openWeather.timezone}</li>
            <li>{openWeather.dt}</li>
            <li>{openWeather.visibility}</li>
            <li>{openWeather.base}</li>
            {/* <li>{openWeather.current.weather[0].main}</li> */}
        </ul>
    );
}

export default LocalWeather;

The console.log in the axiosGet method is breaking the page.