I’m working on the Local Weather App in React and want to get the current user’s location and then display the weather in that location. However, I need to ensure that the weather is displayed once I received the latitude and longitude. I created the below functions but don’t know how to make the other one run after the first one finished executing.
Can someone please help?
const [latitude, setLatitude] = useState(null);
const [longitude, setLongitude] = useState(null);
// get latitude and longitude
const getGeolocation = () => {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
setStatus(null)
setLatitude(position.coords.latitude);
setLongitude(position.coords.longitude);
},
() => {
setStatus('Unable to retrieve your location');
});
} else {
setStatus('Geolocation is not supproted by your broswer')
}
}
// get weather information
const fetchCurrentWeather = () => {
fetch(`${url}api/current?lat=${latitude}&lon=${longitude}`)
.then(response => response.json())
.then(data => {
// returns data
})
}
Thank you!