skip to Main Content

In below simple app I am retrieving value of coordinate through expo-location and storing in a usestate, but some how console value for both latitude and longitude return undefined.Any help would be highly appreciated. I want to retrieve both coordinate value on loading this component and in later state use them to set location in map.

import { StatusBar } from 'expo-status-bar';
import { useRef, useState, useEffect } from 'react';
import { Button, StyleSheet, Text, View } from 'react-native';
import MapView, { Callout, Marker, PROVIDER_GOOGLE } from 'react-native-maps';
import * as Location from 'expo-location';

export default function App() {

  const [location, setLocation] = useState();
  const [address, setAddress] = useState();
  const [latitude, setLatitude] = useState();
  const [longitude, setLongitude] = useState();
  const [errorMsg, setErrorMsg] = useState(null);



  useEffect(() => {
    (async () => {
      
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
        return;
      }
     
    
    })();
    Location.installWebGeolocationPolyfill();
    navigator.geolocation.getCurrentPosition(pos =>{
      setLongitude(pos.coords.longitude);
       setLatitude(pos.coords.latitude);     
       console.log("latitude: ", latitude);
       console.log("longitude: ", longitude);
       });
   // 
  }, []);

2

Answers


  1. The thing is setState is asynchronous. When you call these functions, React does not immediately update the state.
    If you want you can use another useEffect to log the updated values whenever the state changes:

    useEffect(() => {
      console.log("latitude: ", latitude);
    }, [latitude]);
    
    useEffect(() => {
      console.log("longitude: ", longitude);
    }, [longitude]);
    
    Login or Signup to reply.
  2. because react does not immediately update the state you can log the new values:

    console.log("latitude: ", pos.coords.longitude);
    console.log("longitude: ", pos.coords.latitude);
    

    now it’s the same values like the states.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search