Почему не выводятся данные из fetch запроса в элементы на React?
class MyWeather extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentDidMount() {
fetch('https://api.openweathermap.org/data/2.5/weather?q=ODESA&units=metric&APPID=5d066958a60d315387d9492393935c19')
.then(response => response.json())
.then(data => this.setState({ data }));
console.log(this.state.data);
}
render() {
const { data } = this.state;
const srcURL = `https://openweathermap.org/img/w/${data.weather[0]['icon']}.png`;
return (
<div>
<h1>City: {data.name}</h1>
<p>Temperature: {Math.round(data.main.temp)}°C</p>
<p>Pressure: {data.main.pressure} hPa</p>
<p>Description: {data.weather[0]['description']}</p>
<p>Humidity: {data.main.humidity}%</p>
<p>Speed: {data.wind.speed}m/s</p>
<p>Degree: {data.wind.deg}°</p>
<img src={srcURL} alt='Weather' title='Weather'/>
</div>
);
}
}
ReactDOM.render(
<MyWeather />,
document.body
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
В консоли есть ошибка:
TypeError: Cannot read properties of undefined (reading '0')
Источник: Stack Overflow на русском