-1

I declared a variable names with an empty array value out of the function, then used it inside the function to assign returned value, then I want to use it outside this function, but outside the function this variable remains empty. Please explain what I'm doing wrong.

  handleUpdateInputBusinessName = (searchText) => {
    var names = [];
    var displaySuggestions = function(predictions, status) {
      if (status !== google.maps.places.PlacesServiceStatus.OK) {
        alert(status);
        return;
      }

      predictions.forEach(function(prediction) {
        let name = prediction.description;
        names.push(name);
      });

      console.log('names_in:', names); // valid predictions from Google Maps Service
      return names;    
    };

    console.log('names_out:', names); // []

    var service = new google.maps.places.AutocompleteService();
    service.getQueryPredictions({ input: searchText, types: '(cities)'    
    }, displaySuggestions);
DKras
  • 51
  • 4

2 Answers2

0

Here's the boiled down version:

a = [];
var b = () => {
  a.push(1);
  console.log('inside:', a)
};
console.log('outside:', a);
b();

The "outside" console log is running before the displaySuggestions function is called, so the data is not yet populated in the array.

Zevgon
  • 556
  • 4
  • 13
0

you have to use js anonymous function syntax to increse the scope of names array below is the code.

 handleUpdateInputBusinessName = (searchText) => {
    var names = [];
    var displaySuggestions = (predictions, status) => {
      if (status !== google.maps.places.PlacesServiceStatus.OK) {
        alert(status);
        return;
      }
  predictions.forEach((prediction) => {
    let name = prediction.description;
    names.push(name);
  });

  console.log('names_in:', names); // valid predictions from Google Maps Service
  return names;    
};

console.log('names_out:', names); // []

var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({ input: searchText, types: '(cities)'    
}, displaySuggestions);

hope this heps.

mindaJalaj
  • 448
  • 3
  • 11