UNPKG

@hhgtech/hhg-components

Version:
86 lines (82 loc) 2.97 kB
'use strict'; var tslib_es6 = require('./tslib.es6-92cccef3.js'); var React = require('react'); const formatAutoCompleteAddress = (addresses) => { if (!addresses || addresses.length < 1) return []; return addresses.map((s) => ({ placeId: s.place_id, description: s.description, rawData: s, })); }; const IS_SSR = typeof window === 'undefined'; // https://developers.google.com/maps/faq#languagesupport const GOOGLE_API_LANGUAGE = { VN: 'vi', ID: 'id', TH: 'th', MY: 'ms', TW: 'zh-TW', KH: 'km', MM: 'my', IN: 'hi', PH: 'en', }; const GOOGLE_API_KEY = 'AIzaSyD9AbNa4AFwr8eNVs90G1YhQLhfWJ6KncU'; const googleAutocomplete = (text = '', countrycode = '', languageCountrycode = 'vi') => tslib_es6.__awaiter(void 0, void 0, void 0, function* () { return new Promise((resolve, reject) => { if (!text) { return reject('Need valid text input'); } if (IS_SSR) { return reject('Need valid window object'); } try { new window.google.maps.places.AutocompleteService().getPlacePredictions(Object.assign(Object.assign({ input: text }, (countrycode ? { componentRestrictions: { country: countrycode }, } : {})), { language: GOOGLE_API_LANGUAGE[languageCountrycode] }), resolve); } catch (e) { reject(e); } }); }); const usePlacesAutocomplete = (text = '', countrycode = '', languageCountrycode = '', debounceTimeout = 500) => { const [predictions, setPredictions] = React.useState([]); const [isLoading, setIsLoading] = React.useState(false); React.useEffect(() => { let handleDebounce; if (text) { handleDebounce = window.setTimeout(() => tslib_es6.__awaiter(void 0, void 0, void 0, function* () { if (!text) { setPredictions([]); return; } try { setIsLoading(true); const nextPredictions = yield googleAutocomplete(text, countrycode, languageCountrycode); setPredictions(formatAutoCompleteAddress(nextPredictions)); } catch (e) { console.error(e); } finally { setIsLoading(false); } }), debounceTimeout); } else if (predictions.length) { setPredictions([]); } return () => { window.clearTimeout(handleDebounce); }; }, [text, debounceTimeout, countrycode]); return { isLoading, predictions }; }; exports.GOOGLE_API_KEY = GOOGLE_API_KEY; exports.GOOGLE_API_LANGUAGE = GOOGLE_API_LANGUAGE; exports.usePlacesAutocomplete = usePlacesAutocomplete;