I am using axios to fetch weather api data with useEffect.
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Header } from './Header';
export const CurrentCity = () => {
const [weather, setWeather] = useState({});
console.log('weather', weather);
console.log(weather.weather[0].icon);
useEffect(() => {
async function getData() {
const url = `https://api.openweathermap.org/data/2.5/weather?q=Berlin&appid=${process.env.REACT_APP_WEATHER_KEY}`;
try {
const response = await axios.get(url);
setWeather(response.data);
} catch (err) {
console.log(err);
}
}
getData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div>
<Header api={weather} />
</div>
);
};
This is the result of console.log(data) :
{coord: {…}, weather: Array(1), base: "stations", main: {…}, visibility: 10000, …}
coord: {lon: 13.41, lat: 52.52}
weather: Array(1)
0: {id: 802, main: "Clouds", description: "scattered clouds", icon: "03n"}
length: 1
__proto__: Array(0)
base: "stations"
main: {temp: 278.43, feels_like: 270.3, temp_min: 276.48, temp_max: 280.37, pressure: 1009, …}
visibility: 10000
wind: {speed: 8.7, deg: 270, gust: 13.9}
clouds: {all: 40}
dt: 1584060559
sys: {type: 1, id: 1275, country: "DE", sunrise: 1584077086, sunset: 1584119213}
timezone: 3600
id: 2950159
name: "Berlin"
cod: 200
__proto__: Object
If I console.log the data I am getting by
console.log('weather', weather);
console.log(weather.weather[0].icon);
the error messages says, it cannot read the property of [0],
or if I try to access deeper into 'wind' for example,
console.log(weather.wind.speed);
it says, cannot read the property of speed.
If it is an array that I want to have access to, I would use [0] or if it's an object, I would use dot notation.
Moreover I am passing down the data which I got from axios to Header.js
import React from 'react';
export const Header = props => {
console.log(props.api.name);
return (
<div>
<h1>{props.api.name}</h1>
</div>
);
};
Same thing happens when I try to go deeper into the other data.
I would like to find out what I am missing, Thank you all in advance! And also want to know what the difference is between 1 and 2, and which one should I be using for current situation.
const [weather, setWeather] = useState({});
const [weather, setWeather] = useState(null);