javascriptreactjsreact-hooksgeocode

I am not able to store the returned value of a javaScript function (of Geocoding) in a variable


I am trying to store the latitude and longitude values I calculated inside the function. If I console.log both the values inside the function, it is working fine. However, if I return those values to use them somewhere else, then I cannot do so (it throws an error in the console as having this coordinates list as undefined). Whatever I am returning from this Geocoding function, it shows undefined in the console. Here is the code snippet:

function Geocoding() {
  axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
    params: {
      address: enteredAddress,
      key: 'my API key here'
    }
  })
    .then(function (response) {
      var lat = response.data.results[0].geometry.location.lat;
      var lng = response.data.results[0].geometry.location.lng;
      return [lat, lng];
    })

    .catch(function (error) {
      console.log(error);
    });
}

const submitHandler = (event) => {
  event.preventDefault();

  var coordinates = Geocoding();

  const userInput = { //object
    location: {
      latitude: coordinates[0],
      longitude: coordinates[1],
      maxDistance: enteredDistance
    },
    instrumentType: enteredInstrumentType,
    awardNumber: enteredAwardNumber,
    includeRetired: enteredIRI
  };
  props.onSaveUserInput(userInput);

  setEnteredAddress('');
  setEnteredDistance('');
  setEnteredInstrumentType('');
  setEnteredAwardNumber('');
  setEnteredIRI('');
};

Solution

  • The problem is that the Geocoding is not returning anything. Anyway, I'd convert the code to async/await if possible so it's easier to comprehend. Take a look below at the same code fixed with async/await.

    async function Geocoding() {
      try {
        const response = await axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
          params: {
            address: enteredAddress,
            key: 'my API key here'
          }
        })
        
        var lat = response.data.results[0].geometry.location.lat;
        var lng = response.data.results[0].geometry.location.lng;
        return [lat, lng];
      } catch (error) {
        console.error(error)
        throw error;
      }
    }
    
    const submitHandler = async (event) => {
      event.preventDefault();
    
      var coordinates = await Geocoding();
    
      const userInput = { //object
        location: {
          latitude: coordinates[0],
          longitude: coordinates[1],
          maxDistance: enteredDistance
        },
        instrumentType: enteredInstrumentType,
        awardNumber: enteredAwardNumber,
        includeRetired: enteredIRI
      };
      props.onSaveUserInput(userInput);
    
      setEnteredAddress('');
      setEnteredDistance('');
      setEnteredInstrumentType('');
      setEnteredAwardNumber('');
      setEnteredIRI('');
    };
    

    Notice that to call Geocoding you need to use also async/await or use the Promise.then like Geocoding().then((coordinates) => {...})