I've hit a roadblock with a personal react project of mine where I'm building a weather app.
The first phase in my project is to get weather based on a user's geolocation.
I have the following code:
const API_KEY = process.env.REACT_APP_WEATHER_API_KEY;
// retreive API data, display forecast info
export default function GeolocationForecast() {
// initialize state variables for weather data and geo coordinates
const [data, setData] = useState('');
const [userLat, setUserLat] = useState(null);
const [userLon, setUserLon] = useState(null);
const [userStatus, setUserStatus] = useState(null);
useEffect(() => {
fetchUserGeolocationAndForecast();
}, []);
// get user's geo coordinates, insert into API query, return API response results
async function fetchUserGeolocationAndForecast() {
(function getUserGeoData() {
if (!navigator.geolocation) {
setUserStatus('Error: Geolocation is not supported by your browser');
} else {
setUserStatus('Loading...');
navigator.geolocation.getCurrentPosition(
(position) => {
// update status and lat and lng position for user
setUserStatus(null);
setUserLat(position.coords.latitude);
setUserLon(position.coords.longitude);
console.log('geocoords saved to state')
console.log('user geo data', userLat, userLon, userStatus);
}, () => {
setUserStatus('Unable to retrieve your location :(');
});
}
})();
const apiUrl = `https://api.openweathermap.org/data/2.5/onecall?lat=${userLat}&lon=${userLon}&units=imperial&appid=${API_KEY}`;
axios.get(apiUrl)
.then((res) => {
// forecast data response from API
const forecastData = res.data.daily;
// update state variable with response data
setData(forecastData);
console.log('geoForecast res', forecastData);
console.log('full geoForecast res', res);
}).catch(error => console.error(`Error: ${error}`));
}
return (
<div>
<span><h1>7-Day Forecast</h1><LocationOnIcon fontSize="large" /></span>
{/* <h4>{userStatus}</h4> */}
<GeoForecast data={data} />
</div>
);
};
My goal: get the user's longitude and latitude BEFORE querying the API endpoint (variable defined as apiUrl in the code above). I tried turning the getUserGeoData function into an IIFE to test out with but I'd like to implement async/await instead of an IIFE would make more sense.
That's where I'm stuck. If you need more info, happy to provide it. Any help/criticism is welcome.