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

205
Views
React - Why is geolocation state undefined when accessing it from another function

I'm trying to get the latitude and the longitude from geoLocation and use it to fetch data from a weather api. The problem however is that as soon as I pass latitude or longitude state into my fetchWeather function and try to access it, it only works once. If I reload the page the latitude and longitude state is shown as undefined, which is the initialstate. It is as if the state is not set again after page refresh. Outside the function the state works fine even after page reload.

function WeatherToday() {
  const [weather, setWeather] = useState([]);
  const [Loading, setLoading] = useState(false);

  const [latitude, setLatitude] = useState();
  const [longitude, setLongitude] = useState();

  const fethGeoLocation = async () => {
    try {
      navigator.geolocation.getCurrentPosition(function (position) {
        setLatitude(position.coords.latitude);
        setLongitude(position.coords.longitude);
      });
    } catch (error) {
      console.warn(error);
    }
  };

  console.log(latitude, longitude);
  // Works on every call

  const fetchWeatherData = async () => {
    try {
      setLoading(true);
      console.log('geolocation', latitude, longitude);
      // does not work, latitude and longitude is undefined
      const res = await fetchWeather(latitude, longitude);
      setWeather(res.data);
      setLoading(false);
    } catch (error) {
      setLoading(false);
      console.warn(error);
    }
  };

  useEffect(() => {
    fethGeoLocation();
    fetchWeatherData();
  }, []);

  if (
    !Loading &&
    weather &&
  ) {
    return (
      <div className={WeatherTodayStyles.container}>
        <Forecast forecast={weather} />
        <HourlyForecast forecast={weather} />
      </div>
    );
  } else {
    return <div>Loading...</div>;
  }
}

export default WeatherToday;
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!