'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;


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source