I am trying to create a weather app using react. While fetching the data from the API, there is an issue that it always return null from the API even after the asynchronous call.
import React, {useEffect, useState } from "react";
export default function App(){
const API_KEY = "somekey";
const [lat, setLat] = useState([]);
const [long, setLong] = useState([]);
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
navigator.geolocation.getCurrentPosition(function (position) {
setLat(position.coords.latitude);
setLong(position.coords.longitude);
});
await fetch(
`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${long}&exclude=hourly,minutely&units=metric&appid=${API_KEY}`
)
.then((res) => res.json())
.then((result) => {
setData(result);
console.log(result);
});
};
fetchData();
}, [lat, long]);
return (
<div className="App">
{(data.main && data.sys && data.weather) ? (
<h1>{data.name}</h1>
) :null}
</div>
);
}
It always executes the second statement in the conditional operator. How do I return the data temperature ,humidity, sunrise etc.?