Skip to content

Instantly share code, notes, and snippets.

@StarpTech
Last active October 12, 2021 13:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StarpTech/59c7b83b8ad96cfb1c9f8f9855c28537 to your computer and use it in GitHub Desktop.
Save StarpTech/59c7b83b8ad96cfb1c9f8f9855c28537 to your computer and use it in GitHub Desktop.
Algolia Places React Hook - SSR compatible - https://github.com/algolia/places
// ###################
// #### 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