A React hook for Google Places Autocomplete with flexible options and built-in session token management.
This hook is a wrapper around the Google Maps Places API. It provides a flexible and customizable autocomplete experience, with debouncing, location restriction, and session token management.
There's also an input component version that includes this hook, easily embeddable in a shadcn form with autocomplete functionality. Visit autocompletecn website for further information.
import { useAutocomplete } from "@/hooks/use-autocomplete";
const {
places,
getSuggestions,
getPlaceDetails,
isLoaded,
isStale,
error,
} = useAutocomplete(key, {
libraries: ['places'],
debounceMs: 350
});
...
getSuggestions("your value", {
locationRestriction: {
north: 10,
east: 10,
south: 10,
west: 10,
},
});import { AutocompleteInput } from "@/components/autocomplete-input";
const handlePlaceSelect = (place: PlaceDetails) => {
form.setValue("street", `${place.route} ${place.streetNumber}` ?? "");
form.setValue("city", place.city ?? "");
form.setValue("country", place.country ?? "");
form.setValue("postalCode", place.postalCode ?? "");
form.trigger();
};
/* within a react-hook-form */
<Controller
control={form.control}
name="street"
render={({ field }) => (
<Autocomplete
apiKey={process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}
onPlaceSelect={handlePlaceSelect}
placeholder="Type an address..."
fetchParams={{ includedPrimaryTypes: ["route"] }}
{...field}
/>
)}
/>