From bf8df6eb49367a1f87b9ec2803af71fbaf96ffc5 Mon Sep 17 00:00:00 2001 From: Oleg Hovsepyan Date: Wed, 11 Sep 2024 01:50:22 +0400 Subject: [PATCH] Fixed the GitHub issue (#10) --- src/index.tsx | 51 +++++++++++++++++++++++---------------------------- 1 file changed, 23 insertions(+), 28 deletions(-) diff --git a/src/index.tsx b/src/index.tsx index 4613224..a474f54 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -95,8 +95,6 @@ export const GeoapifyGeocoderAutocomplete = ({ const apiKey = React.useContext(GeoapifyApiKey); let geocoderContainer: HTMLDivElement | null; - let initialized = false; - const geocoderAutocomplete: MutableRefObject< GeocoderAutocomplete | undefined > = useRef(); @@ -159,34 +157,22 @@ export const GeoapifyGeocoderAutocomplete = ({ },[]); useEffect(() => { - if (initialized) { - if (geocoderAutocomplete.current) { - geocoderAutocomplete.current.off("select", onSelect); - geocoderAutocomplete.current.off("suggestions", onSuggestions); - geocoderAutocomplete.current.off("input", onUserInput); - geocoderAutocomplete.current.off("close", onClose); - geocoderAutocomplete.current.off("open", onOpen); - } - - return; + if(!geocoderAutocomplete.current) { + geocoderAutocomplete.current = new GeocoderAutocomplete( + geocoderContainer as HTMLDivElement, + apiKey, + { + placeholder: placeholderValue || "", + addDetails: addDetailsValue, + skipIcons: skipIconsValue, + skipSelectionOnArrowKey: skipSelectionOnArrowKeyValue, + allowNonVerifiedHouseNumber: allowNonVerifiedHouseNumberValue, + allowNonVerifiedStreet: allowNonVerifiedStreetValue, + debounceDelay: debounceDelayValue || 100 + } + ); } - initialized = true; - - geocoderAutocomplete.current = new GeocoderAutocomplete( - geocoderContainer as HTMLDivElement, - apiKey, - { - placeholder: placeholderValue || "", - addDetails: addDetailsValue, - skipIcons: skipIconsValue, - skipSelectionOnArrowKey: skipSelectionOnArrowKeyValue, - allowNonVerifiedHouseNumber: allowNonVerifiedHouseNumberValue, - allowNonVerifiedStreet: allowNonVerifiedStreetValue, - debounceDelay: debounceDelayValue || 100 - } - ); - geocoderAutocomplete.current.on("select", onSelect); geocoderAutocomplete.current.on("suggestions", onSuggestions); geocoderAutocomplete.current.on("input", onUserInput); @@ -196,6 +182,15 @@ export const GeoapifyGeocoderAutocomplete = ({ if (sendGeocoderRequestFuncValue) { geocoderAutocomplete.current.setSendGeocoderRequestFunc(sendGeocoderRequestFuncValue) } + return () => { + if (geocoderAutocomplete.current) { + geocoderAutocomplete.current.off("select", onSelect); + geocoderAutocomplete.current.off("suggestions", onSuggestions); + geocoderAutocomplete.current.off("input", onUserInput); + geocoderAutocomplete.current.off("close", onClose); + geocoderAutocomplete.current.off("open", onOpen); + } + }; }, []); useEffect(() => {