All Projects → timc1 → use-google-autocomplete

timc1 / use-google-autocomplete

Licence: MIT license
A simple React Hook API that returns Google Autocomplete results with session_token handling.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to use-google-autocomplete

idiots.win
Google Autocomplete Guessing Game
Stars: ✭ 26 (-3.7%)
Mutual labels:  google-autocomplete
trashed
Trashed is an organizational tool designed to help users keep their communities clean.
Stars: ✭ 13 (-51.85%)
Mutual labels:  google-maps-api
use-latest
No description or website provided.
Stars: ✭ 18 (-33.33%)
Mutual labels:  hooks
my eu
Code and data for myeu.uk - find out what the EU has done for your area
Stars: ✭ 18 (-33.33%)
Mutual labels:  google-maps-api
searchmap
Find places and Draw on Map using Google Maps API
Stars: ✭ 53 (+96.3%)
Mutual labels:  google-maps-api
react-ui-hooks
🧩Simple repository of React hooks for building UI components
Stars: ✭ 20 (-25.93%)
Mutual labels:  hooks
ReaLocate
ASP.NET MVC 5 Real Estate Application
Stars: ✭ 18 (-33.33%)
Mutual labels:  google-maps-api
map
Interactive map of Fruška gora, Serbia
Stars: ✭ 13 (-51.85%)
Mutual labels:  google-maps-api
google-maps-v3-opacity-control
Custom overlay opacity control for use with Google Maps JavaScript API V3
Stars: ✭ 17 (-37.04%)
Mutual labels:  google-maps-api
react-hooks-form
React Forms the Hooks Way
Stars: ✭ 25 (-7.41%)
Mutual labels:  hooks
farmers-market-finder
[ARCHIVED] Find and display farmers market locations on map
Stars: ✭ 23 (-14.81%)
Mutual labels:  google-maps-api
airbnb-map-search
Airbnb Map Search Page Rebuilt with Vue
Stars: ✭ 32 (+18.52%)
Mutual labels:  google-maps-api
on-outside-click-hook
A React custom hook to detect clicks which triggers outside the element and then fire an event.
Stars: ✭ 17 (-37.04%)
Mutual labels:  hooks
arduino-google-maps-api
An Arduino library for communicating with the Google Maps Api
Stars: ✭ 42 (+55.56%)
Mutual labels:  google-maps-api
react-useForm
World's simplest React hook to manage form state
Stars: ✭ 30 (+11.11%)
Mutual labels:  hooks
My Android Garage
A quick reference guide for Android development.
Stars: ✭ 66 (+144.44%)
Mutual labels:  google-maps-api
project sunroof india
Analyzed Google Satellite images to generate a report on individual house rooftop's solar power potential
Stars: ✭ 74 (+174.07%)
Mutual labels:  google-maps-api
uni-design
基于React hooks的一套基础组件
Stars: ✭ 22 (-18.52%)
Mutual labels:  hooks
dobux
🍃 Lightweight responsive state management solution.
Stars: ✭ 75 (+177.78%)
Mutual labels:  hooks
react-generate-context
A helper function for reducing React Context boilerplate
Stars: ✭ 24 (-11.11%)
Mutual labels:  hooks

use-google-autocomplete ⌨️

A tiny React Hook that returns Google Autocomplete results with session_token handling.

Problem

Google's Maps Javascript SDK gives us a default autocomplete experience, with a slightly customizable UI through class names; however, if we want to create a ground up search experience, we'll need to use their REST API. We want to have a hook that does something like this:

demo

The two primary things we need to focus on are:

1. Handle session_tokens

Every time we send a request to the REST endpoint, we need to pass a session_token in order for Google to group shared calls together for billing purposes. Google recommends uuid4 ids, and after a bit of research, 3 minutes is the limit for the lifetime of a session_token, though we need to refresh the session_token when we make a new query to fetch more details about a specific place.

2. Debounce API calls

We dont' want to be sending an API call on every single keystroke, so we'll need to debounce each keystroke and only call the API when a user finishes typing.

The Solution

use-google-autocomplete handles session_tokens by using the recommended uuid4/v4 package to generate unique ids, renewing every 180000ms (3 minutes), and when a user calls getPlaceDetails() to fetch more information regarding a specific place.

The returned values from useGoogleAutocomplete will allow us to focus on creating a custom UI.

Usage

yarn add use-google-autocomplete

or

npm install use-google-autocomplete
import useGoogleAutocomplete from 'use-google-autocomplete'

const App = () => {

  // This will update each time a new `query` prop is passed.
  const { results, isLoading, error, getPlaceDetails } = useGoogleAutocomplete({
    apiKey: '<API_KEY>',
    query: 'New York',
    options: {
      types: '(cities)',
    },
  })


  return (
    <ul>
      {results.predictions.map(prediction => (
        <li key={prediction.place_id}>
          <Component prediction={prediction} />
        </li>
      })
    </ul>
  )
}

Props

apiKey

String value of your Google API key. Make sure to enable the Maps API in your console.

type

String value of 'places' or 'query' | defaults to 'places' This will determine if we use 'autocomplete' or 'queryautocomplete' (reference)

query

String value of a search query.

options

Object of Google options

property type description
types string (cities), geocode, establishments, or address
language string Language for results to return
location string 37.7749, -122.4194 or San Francisco, CA
radius number Results within the radius of the search (meters)
strictbounds boolean Returns only those places that are strictly within the region defined by location and radius
offset number The position, in the input term, of the last character that the service uses to match predictions.

Return values

results

Array of Google search results

isLoading

Boolean | True when fetching Google API data

error

Null or string value of the current error, if there is any.

getPlaceDetails

Function getPlaceDetails( placeId: string, placeDetailOptions: { fields?: string[], region?: string, language?: string })

This function must be used if you are trying to get more information about a place (ex; latitude/longitude). It'll fetch the Place data and renew our session_token.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].