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
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:because react does not immediately update the state you can log the new values:
now it’s the same values like the states.