Search code examples
javascriptreactjspromisegoogle-geocoder

React Geocode package returns fulfilled Promise object in React


I have a piece of state which is meant to receive user location on page load.

  const [userLocation, setUserLocation] = useState({
    lat: null,
    lng: null,
    userAddress: ''
  })

I have created a getAddress function which is meant to return a string value of an address based on coordinates using the react Geocode npm package

  const getAddress = async (lat, lng) => {
    try {
      const res = await Geocode.fromLatLng(lat, lng)
      const address = res.results[0].formatted_address;
      return address

    } catch (err) {
      console.log(err.message)
    }

  }

my getUserLocation function is run in a useEffect on page load

  const getUserLocation = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else {
      console.log("Geolocation is not supported by this browser.");
    }
  }

  const showPosition = (position) => {
    setUserLocation({
      ...userLocation,
      lat: position.coords.latitude,
      lng: position.coords.longitude,
      userAddress: getAddress(position.coords.latitude, position.coords.longitude)
    })
  }

my userLocation object is returning as follows:

USER LOCATION 
{lat: 43.829601, lng: -79.470408, userAddress: Promise}
lat: 43.829601
lng: -79.470408
userAddress: Promise
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: "126 Seabreeze Ave, Thornhill, ON L4J 9H1, Canada"
[[Prototype]]: Object

I would like the promise result value to be returned and nothing else obviously. Is there any solution to this?


Solution

  • Because async functions return a promise, calling one will give you back the promise, not the result.

    Here you are calling getAddress directly:

    userAddress: getAddress(position.coords.latitude, position.coords.longitude)
    

    But if you want the result, you'll have to make showPosition async, and await the result from getAddress:

    const showPosition = async (position) => {
        setUserLocation({
          ...
          ...
          ...
          userAddress: await getAddress(position.coords.latitude, position.coords.longitude)
        })
      }