I am trying to create a WeatherApp using React and OpenWeathermap API as beginner project. After fetching the data from the API, I am not able to return any component as it always returns null from the conditional statement.
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) {
console.log(position.coords.latitude);
setLat([position.coords.latitude]); //sets latitude
setLong([position.coords.longitude]); //sets 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(data);
});
};
fetchData();
}, [lat, long]);
return (
<div className="App">
{(typeof data.main !== 'undefined') ? (
<h1>{data.name}</h1> //doesnt execute
) :null}
</div>
);
}
The project is based on this example:https://www.freecodecamp.org/news/learn-react-by-building-a-weather-app/