I’m writing the below function that should get the user’s current location and then update the predefined location properties:
export const getCurrentLocation = () => {
const location = {
userLat: '5',
userLng: ''
}
navigator.geolocation.getCurrentPosition(
(position) => {
//getting the Longitude from the location json
const currentLongitude = JSON.stringify(position.coords.longitude);
//getting the Latitude from the location json
const currentLatitude = JSON.stringify(position.coords.latitude);
location.userLat = currentLatitude;
console.log('lat: ', location.userLat);
},
(error) => {
console.warn(error);
},
{
enableHighAccuracy: false,
timeout: 30000,
maximumAge: 1000
},
);
return (
location
);
}
I equated location.userLat
to currentLatitude
and this logs correctly on the console, however when the function is done running, the produced userLat
is still its initial value of 5
. I alternatively tried using useState
hooks to update the value but got the error of invalid hook calls
. Any tips or suggestions on how to make it reflect the currentLatitude
value will be appreciated.
2
Answers
From what I can tell it seems that
getCurrentPosition
is an asynchronous function. Note that this doesn’t mean it’s declaredasync
or that it returns a Promise object that can beawait
-ed on.You can convert your
getCurrentLocation
function to anasync
function and wrap thegetCurrentPosition
call in a Promise.Consuming code:
As @Drew stated getting the location is happening asynchronously, so that
retun
is happening before theconsole log
. Another way of talking this is to transform your function to ahook
, so you will be able to useuseState
. Like so:And you would use it as below. First you would get
fetchingLocation
containingtrue
, then it becomesfalse
, and whether the location is successful or not, you would geterror
containing a message orlocation
containing the actual latitude and longitude.