How to use async await with the HTML5 getCurrentPosition()

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!

React.useEffect(() => {
  // get  weather information
  const fetchCurrentWeather = () => {
    fetch(`${url}api/current?lat=${latitude}&lon=${longitude}`)
      .then((response) => response.json())
      .then((data) => {
        // returns data
      });
  };

  if (latitude && longitude) {
    fetchCurrentWeather();
  }
}, [latitude, longitude]);
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.