title: React - How to restrict Google Places API results to specific countries dynamically
body: <p>I am trying to restrict Autocomplete results to a country dynamically. Right now i am able to initialize the API script and get reslts for the default country, but once a user changes the country, i am running the following script which is just not doing anything:</p>
  <pre><code>setAutocompleteCountry = () =&gt; {
      if (this.state.country == 'all') {
        autoComplete.setComponentRestrictions({'country': []});
      } else {
        autoComplete.setComponentRestrictions({'country': country});
      }
  }
  </code></pre>
  <p>I appreciate any insights and here is the relevant code in the component:</p>
  <pre><code>
  let autoComplete;
  let country = 'vn'
  
  class ServiceableAreas extends Component {
      constructor(props) {
          super(props)
          this.state = {
              query: '',
              country: 'th'
          }
          this.autoCompleteRef = React.createRef(null);
      }
  
      componentDidUpdate(prevProps, prevState) {
          const { city } = this.props.values;
          if (city !== prevProps.values.city) {
              if (city !== null) {
  
                  if (city === 'Bangkok') {
                      country = 'th'
                  }
                  else if (city === 'Vientiane') {
                      country = 'la'
                  }
                  else if (city === 'Hoh Chi Min') {
                      country = 'vn'
                  }
                  this.setAutocompleteCountry()
              }
          }
      }
  
      componentDidMount() {
          this.loadScript(
              &quot;https://maps.googleapis.com/maps/api/js?key=AIzaSyD4FpFjf7nQ0LDaz3qi1EShX2p4Yy0rnxo&amp;libraries=places&quot;,
              () =&gt; this.handleScriptLoad(this.setQuery, this.autoCompleteRef)
            );
      }
  
      setQuery = (query) =&gt; {
          this.setState({query})
      }
      
      // dynamically load JavaScript files in our html with callback when finished
      loadScript = (url, callback) =&gt; {
          let script = document.createElement(&quot;script&quot;); // create script tag
          script.type = &quot;text/javascript&quot;;
      
          // when script state is ready and loaded or complete we will call callback
          if (script.readyState) {
          script.onreadystatechange = function() {
              if (script.readyState === &quot;loaded&quot; || script.readyState === &quot;complete&quot;) {
              script.onreadystatechange = null;
              callback();
              }
          };
          } else {
              script.onload = () =&gt; callback();
          }
      
          script.src = url; // load by url
          document.getElementsByTagName(&quot;head&quot;)[0].appendChild(script); // append to head
      };
  
      // handle when the script is loaded we will assign autoCompleteRef with google maps place autocomplete
      handleScriptLoad = (updateQuery, autoCompleteRef) =&gt; {
          // assign autoComplete with Google maps place one time
          autoComplete = new window.google.maps.places.Autocomplete(
          autoCompleteRef.current,
          { types: [&quot;(regions)&quot;], componentRestrictions: { country: country } }
          );
          // autoComplete.setFields([&quot;address_components&quot;, &quot;formatted_address&quot;]); // specify what properties we will get from API
          autoComplete.setFields([&quot;address_components&quot;]); // specify what properties we will get from API
          // add a listener to handle when the place is selected
          autoComplete.addListener(&quot;place_changed&quot;, () =&gt;
              this.handlePlaceSelect(updateQuery)
          );
      }
  
      // Set the country restriction based on user input.
      setAutocompleteCountry = () =&gt; {
          if (this.state.country == 'all') {
            autoComplete.setComponentRestrictions({'country': []});
          } else {
            autoComplete.setComponentRestrictions({'country': country});
          }
      }
  
      handlePlaceSelect = async (updateQuery) =&gt; {
          const addressObject = await autoComplete.getPlace(); // get place from google api
          const query = addressObject.formatted_address;
          updateQuery(query);
          console.log(addressObject);
          const _area = addressObject.address_components.filter(item =&gt; item.types.filter(t =&gt; t === 'sublocality_level_1').length &gt; 0)[0]
          //console.log('_AREA: ', _area)
          if (_area !== undefined) {
              const area = _area.long_name;
              console.log('AREA: ', area)
              if (this.props.values.serviceableAreas.indexOf(area) === -1) {
                  const areas = [...this.props.values.serviceableAreas, area]
                  this.props.setServiceableAreas(areas)
                  this.setState({query: ''})
              }
              else {
                  this.setState({query: ''})
                  this.focus()
              }
          }
          else {
              this.setState({query: ''})
              this.focus()
          }
        }
   
      render() {
          const { values } = this.props;
    
                &lt;div&gt;
                  &lt;Grid container spacing={1}&gt;
                      &lt;Grid item md={12}&gt;
                          &lt;TextField
                              inputRef={this.autoCompleteRef}
                              label='Area'
                              placeholder=&quot;Enter area&quot;
                              onChange={event =&gt; this.setQuery(event.target.value)}
                              value={this.state.query}
                              InputProps={{ disableUnderline: true }}
                              fullWidth
                          /&gt;
                      &lt;/Grid&gt;
                  &lt;/Grid&gt;        
              &lt;/div&gt;
          )
      }
  }
              
  export default ServiceableAreas
  
  </code></pre>