({ onChange, onClick, onClose, onSelect, ...rest })
| 39 | onChange?: (place?: Place) => void |
| 40 | onSelect?: (place?: Place) => void |
| 41 | } |
| 42 | |
| 43 | export const LocationAutocompleteInput: FC< |
| 44 | React.PropsWithChildren<LocationAutocompleteInputProps> |
| 45 | > = ({ onChange, onClick, onClose, onSelect, ...rest }) => { |
| 46 | const [suggestions, setSuggestions] = useState< |
| 47 | Array<AutocompleteInputOptionType> |
| 48 | >([]) |
| 49 | const [ready, setReady] = useState(false) |
| 50 | const [isLoading, setIsLoading] = useState(false) |
| 51 | const autocompleteServiceRef = |
| 52 | useRef<google.maps.places.AutocompleteService | null>(null) |
| 53 | const geocoderRef = useRef<google.maps.Geocoder | null>(null) |
| 54 | |
| 55 | useEffect(() => { |
| 56 | if (!isGooglePlacesLoaded()) { |
| 57 | window.__googleMapsCallback = () => { |
| 58 | setReady(true) |
| 59 | } |
| 60 | return |
| 61 | } |
| 62 | |
| 63 | setReady(true) |
| 64 | }, []) |
| 65 | |
| 66 | useEffect(() => { |
| 67 | if (!ready || !isGooglePlacesLoaded()) return |
| 68 | autocompleteServiceRef.current = |
| 69 | new google.maps.places.AutocompleteService() |
| 70 | geocoderRef.current = new google.maps.Geocoder() |
| 71 | }, [ready]) |
| 72 | |
| 73 | useLoadScript({ id: "google-maps-js", src: GOOGLE_PLACES_API_SRC }) |
| 74 | |
| 75 | const fetchSuggestions = async (searchQuery: string) => { |
| 76 | const res = await autocompleteServiceRef.current?.getPlacePredictions({ |
| 77 | input: searchQuery, |
| 78 | types: ["(cities)"], |
| 79 | }) |
| 80 | |
| 81 | return res?.predictions |
| 82 | } |
| 83 | |
| 84 | const updateSuggestions = useCallback(async (value: string) => { |
| 85 | setSuggestions([]) |
| 86 | if (!value.trim()) return |
| 87 | |
| 88 | try { |
| 89 | setIsLoading(true) |
| 90 | const suggestions = await fetchSuggestions(value) |
| 91 | setIsLoading(false) |
| 92 | if (suggestions) { |
| 93 | setSuggestions( |
| 94 | suggestions.map(option => ({ |
| 95 | text: option.description, |
| 96 | value: option.place_id, |
| 97 | })), |
| 98 | ) |
nothing calls this directly
no test coverage detected