Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
Having trouble getting geolocation data before querying an API endpoint

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!