UNPKG

@hhgtech/hhg-components

Version:
82 lines (79 loc) 2.87 kB
import { a as __awaiter } from './tslib.es6-ea4dfe68.js'; import { useState, useEffect } from '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') => __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] = useState([]); const [isLoading, setIsLoading] = useState(false); useEffect(() => { let handleDebounce; if (text) { handleDebounce = window.setTimeout(() => __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 }; }; export { GOOGLE_API_KEY as G, GOOGLE_API_LANGUAGE as a, usePlacesAutocomplete as u };