-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathautocomplete.ts
59 lines (49 loc) · 1.84 KB
/
autocomplete.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import {useContext, useState, useRef, useEffect} from 'react';
import {GoogleMapsContext} from '../google-maps-provider';
export interface AutocompleteProps {
inputField: HTMLInputElement | null;
options?: google.maps.places.AutocompleteOptions;
onPlaceChanged: (place: google.maps.places.PlaceResult) => void;
}
/**
* Hook to get a Google Maps Places Autocomplete instance
* monitoring an input field
*/
export const useAutocomplete = (
props: AutocompleteProps
): google.maps.places.Autocomplete | null => {
const {inputField, options, onPlaceChanged} = props;
const placeChangedHandler = useRef(onPlaceChanged);
const {googleMapsAPIIsLoaded} = useContext(GoogleMapsContext);
const [autocomplete, setAutocomplete] =
useState<google.maps.places.Autocomplete | null>(null);
// Initializes the Google Maps Places Autocomplete
useEffect(() => {
// Wait for the Google Maps API and input element to be initialized
if (!googleMapsAPIIsLoaded || !inputField) {
return (): void => {};
}
if (!google.maps.places) {
throw Error(
"Autocomplete library missing. Add 'places' to the libraries array of GoogleMapsProvider."
);
}
// Create Autocomplete instance
const autocompleteInstance = new google.maps.places.Autocomplete(
inputField,
options
);
setAutocomplete(autocompleteInstance);
// Add places change listener to Autocomplete
autocompleteInstance.addListener('place_changed', () => {
const place = autocompleteInstance.getPlace();
placeChangedHandler.current && placeChangedHandler.current(place);
});
// Clear listeners on unmount
return (): void => {
autocompleteInstance &&
google.maps.event.clearInstanceListeners(autocompleteInstance);
};
}, [googleMapsAPIIsLoaded, inputField, options]);
return autocomplete;
};