BeniaminoBaggins
BeniaminoBaggins

Reputation: 12433

react-native-google-places-autocomplete give it a value rather than just default (initial) value

I have a working <TextInput>:

<TextInput
      placeholder="Location"
      value={props.locationInput.toString()}
      onChangeText={location => props.updateLocationInput(location)}
    />

The props.locationInput is initially '' but as soon as the app starts, a couple of async functions fire and get the users current location which populate the props.locationInput (in a redux store). This means the <TextInput> above displays the users current location when it arrives. I want to basically just do exactly as above, but with a react-native-google-places-autocomplete

The react-native-google-places-autocomplete does initialise with the props.locationInput value. It has a getDefaultValue property eg getDefaultValue={() => props.locationInput.toString()}, however it doesn't change when the props.locationInput changes, so it never displays the users current location because that isn't set when it initialises. How do I get the react-native-google-places-autocomplete to update when props.locationInput changes?

Possibly thinking I may need to not render it until the users current location comes in but that is really messy.

EDIT: Also looking into not using the plugin and instead doing calls to google places API.

Upvotes: 9

Views: 14509

Answers (5)

John Obiofiong
John Obiofiong

Reputation: 9

The way I go about this is to use a useEffect to initialize the value with the setAddressText function provided by GooglePlacesAutocomplete.

const CustomGooglePlacesInput = ({
  setAddress,
  placeholder,
  fetchDetails = false,
  defaultInputValue,
  customStyle,
}) => {
  const [shouldSetDefaultValue, setShouldSetDefaultValue] = useState(true);
  useEffect(() => {
    const cleanUp = setTimeout(() => {
      setShouldSetDefaultValue(false);
    }, 1000);
    return () => cleanUp();
  }, []);


  return (
    <GooglePlacesAutocomplete
      placeholder={placeholder ?? "Search a place"}
      ref={(ref) => {
        if (shouldSetDefaultValue && defaultInputValue !== undefined){
          ref?.setAddressText(defaultInputValue);
         }
        }}
      
         //...rest of your props
         />
      )
      }


export default CustomGooglePlacesInput;

By doing the above, i know that the default value would already be present at most 1 second before the CustomGooglePlacesInput is mounted

Upvotes: 0

Ulises Martinez
Ulises Martinez

Reputation: 1

const ref = useRef<GooglePlacesAutocompleteRef | null>(null);

const handleInputData = () => {
   setTimeout(() => {
        ref?.current?.setAdressTextAndQuery('San Francisco, CA');
    }, 1000);
}

Check this out: https://github.com/FaridSafi/react-native-google-places-autocomplete/pull/898

ps: This will auto fill the input and dynamically select the first address to better match whatever you input.

Upvotes: 0

not_fubar_yet
not_fubar_yet

Reputation: 353

using react functional hooks

        <GooglePlacesAutocomplete
          ...
          ref={ref => {
            ref?.setAddressText('123 myDefault Street, mycity')
          }}
        />  

Upvotes: 3

Simofy
Simofy

Reputation: 143

Late to the game, but there is function named setAddressText.

Example:

setLocation(text) {
  this.placesRef && this.placesRef.setAddressText(text)
}
...
<GooglePlacesAutocomplete
ref={ref => {this.placesRef = ref}}
...
/>

Upvotes: 11

jungleMan
jungleMan

Reputation: 888

On the GooglePlaceAutocomplete component you have to use the onPress event to get the value. Here is an example:

<GooglePlacesAutocomplete
                placeholder='Event Location'
                minLength={2} // minimum length of text to search
                autoFocus={false}
                // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
                listViewDisplayed='auto'    // true/false/undefined
                fetchDetails={true}
                renderDescription={row => row.description} // custom description render
                onPress={(data, details = null) => {
            // 'details' is provided when fetchDetails = true
            this.setState(
              {
                address: data.description, // selected address
                coordinates: `${details.geometry.location.lat},${details.geometry.location.lng}` // selected coordinates
              }
            );
          }}
                textInputProps={{
                  onChangeText: (text) => { console.warn(text) }
                }}
                getDefaultValue={() => ''}

                query={{
                  // available options: https://developers.google.com/places/web-service/autocomplete
                  key: 'XXXXXXXXXXXXXXZXZXXXXXXX',
                  language: 'en', // language of the results
                  types: 'geocode' // default: 'geocode'
                }}

                styles={{
                  textInputContainer: {
                    backgroundColor: 'rgba(0,0,0,0)',
                    borderTopWidth: 0,
                    borderBottomWidth:0,
                  },
                  description: {
                    fontWeight: 'bold',
                  },
                  textInput: {
                  marginLeft: 22,
                  marginRight: 0,
                  height: 38,
                  color: '#5d5d5d',
                  fontSize: 16,
                },
                  predefinedPlacesDescription: {
                    color: '#1faadb'
                  }
                }}
                value={props.location}
                onChangeText={props.onLocationChange}
                renderLeftButton={()  => <Text style={{ marginTop: 12, marginLeft:16, fontSize: 18 }}> Location </Text>}
                nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
                GoogleReverseGeocodingQuery={{
                  // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
                }}
                GooglePlacesSearchQuery={{
                  // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
                  rankby: 'distance',
                  types: 'food'
                }}

                filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities
                debounce={200} // debounce the requests in ms. Set to 0 to remove debounce. By default 0ms.

              />

Upvotes: 2

Related Questions