Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda