Last active
October 12, 2021 13:07
-
-
Save StarpTech/59c7b83b8ad96cfb1c9f8f9855c28537 to your computer and use it in GitHub Desktop.
Algolia Places React Hook - SSR compatible - https://github.com/algolia/places
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ################### | |
// #### React hook ###### | |
// ################### | |
import { useEffect, useRef, useState } from 'react'; | |
/* eslint-disable global-require */ | |
const Places = typeof window !== 'undefined' && require('places.js'); | |
export default function useAlgoliaPlaces({ options, events }) { | |
const algoliaPlacesRef = useRef(); | |
const [container, setContainer] = useState(); | |
useEffect(() => { | |
if (container) { | |
const algoliaPlaces = Places({ ...options, container }); | |
const e = ['onSuggestions', 'onCursorChanged', 'onChange', 'onClear', 'onLimit', 'onError'] | |
.filter((prop) => !!events[prop]) | |
.map((prop) => ({ prop, eventName: prop.substr(2).toLowerCase() })); | |
e.forEach(({ prop, eventName }) => algoliaPlaces.on(eventName, events[prop])); | |
algoliaPlacesRef.current = algoliaPlaces; | |
return () => e.forEach(({ eventName }) => algoliaPlaces.removeAllListeners(eventName)); | |
} | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, [container]); | |
return setContainer; | |
} | |
// ################### | |
// #### Example ###### | |
// ################### | |
import { useCallback } from 'react'; | |
export default function MyComponent() { | |
const setContainer = useAlgoliaPlaces({ | |
options: { | |
language: 'de', | |
countries: ['de'], | |
type: 'address' | |
}, | |
events: { | |
// for example | |
onClear() {}, | |
onChange({ query, rawAnswer, suggestion, suggestionIndex }) {} | |
} | |
}) | |
const algoliaPlacesRef = useCallback((node) => { | |
if (node !== null) { | |
setContainer(node); | |
} | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, []); | |
return <input ref={algoliaPlacesRef} /> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment