Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda