Hello Everyone !
I’m creating a weather website using react.js and openweathermap api. The api is fetched successfully but there is a huge problem when I try to access the data inside it. The code is
import React, { useState, useEffect } from "react";
import Weather from "./Weather";
function Main() {
const [getCity, setGetCity] = useState("bahawalpur");
const [city, setCity] = useState("bahawalpur");
const [data, setData] = useState({});
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=07f2a451090c5d804494d164f12a4024`;
useEffect(() => {
fetch(apiUrl)
.then((res) => res.json())
.then((data) => setData(data));
}, [apiUrl]);
const handleOnChange = (event) => {
setGetCity(event.target.value);
};
const cityChanged = () => {
setCity(getCity);
console.log(data.name);
};
return (
<div className="main">
<div className="container-1">
<input
className="inputField"
type="text"
placeholder="Enter your city"
onChange={handleOnChange}
/>
<button className="submitButton" type="submit" onClick={cityChanged}>
Submit
</button>
</div>
<div className="container-2">
{" "}
<p>
{" "}
<strong>{data.weather[0].main}</strong> // At this line when I call the main in weather object, it shows error
</p>
</div>
</div>
);
}
export default Main;
The error is Uncaught TypeError: Cannot read properties of undefined (reading '0')
The api gives this responce
{
"coord": {
"lon": -122.08,
"lat": 37.39
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 282.55,
"feels_like": 281.86,
"temp_min": 280.37,
"temp_max": 284.26,
"pressure": 1023,
"humidity": 100
},
"visibility": 10000,
"wind": {
"speed": 1.5,
"deg": 350
},
"clouds": {
"all": 1
},
"dt": 1560350645,
"sys": {
"type": 1,
"id": 5122,
"message": 0.0139,
"country": "US",
"sunrise": 1560343627,
"sunset": 1560396563
},
"timezone": -25200,
"id": 420006353,
"name": "Mountain View",
"cod": 200
}
I’ve tried copying code from many sources but nothing works. I know I’m making a huge mistake here.