Skip to content

The open alternative to Salesforce, designed for AI.

Add place autocomplete to calendar event locations (#24686)

Félix Malfait2ede90b0214c
diff --git a/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventComposerFields.tsx b/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventComposerFields.tsx
index 087bc0cb36f..729b95bd9e7 100644
--- a/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventComposerFields.tsx
+++ b/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventComposerFields.tsx
@@ -1,6 +1,7 @@
import { ComposerFieldRow } from '@/activities/components/ComposerFieldRow';
import { ComposerHeader } from '@/activities/components/ComposerHeader';
import { StyledComposerTextInput } from '@/activities/components/ComposerTextInput';
+import { CalendarEventLocationInput } from '@/activities/calendar/components/CalendarEventLocationInput';
import { type useCalendarEventComposer } from '@/activities/calendar/hooks/useCalendarEventComposer';
import { EmailRecipientsFieldInput } from '@/activities/emails/recipients/components/EmailRecipientsFieldInput';
import { useEmailRecipientsDragAndDrop } from '@/activities/emails/recipients/hooks/useEmailRecipientsDragAndDrop';
@@ -139,13 +140,11 @@ export const CalendarEventComposerFields = ({
label={t`Location`}
labelMinWidth={COMPOSER_LABEL_MIN_WIDTH}
>
- <StyledComposerTextInput
- type="text"
- aria-label={t`Location`}
+ <CalendarEventLocationInput
+ ariaLabel={t`Location`}
placeholder={t`Add a location`}
- onChange={(event) =>
- composerState.setLocation(event.target.value)
- }
+ value={composerState.location}
+ onChange={composerState.setLocation}
/>
</ComposerFieldRow>
<ComposerFieldRow
diff --git a/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventLocationInput.tsx b/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventLocationInput.tsx
new file mode 100644
index 00000000000..bfca01a5c45
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventLocationInput.tsx
@@ -0,0 +1,74 @@
+import { StyledComposerTextInput } from '@/activities/components/ComposerTextInput';
+import { PlaceAutocompleteSelect } from '@/geo-map/components/PlaceAutocompleteSelect';
+import { usePlaceAutocomplete } from '@/geo-map/hooks/usePlaceAutocomplete';
+import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';
+import { isDefined } from 'twenty-shared/utils';
+
+const CALENDAR_EVENT_LOCATION_AUTOCOMPLETE_DROPDOWN_ID =
+ 'calendar-event-location-autocomplete-dropdown';
+
+type CalendarEventLocationInputProps = {
+ ariaLabel: string;
+ placeholder: string;
+ value: string;
+ onChange: (value: string) => void;
+};
+
+export const CalendarEventLocationInput = ({
+ ariaLabel,
+ placeholder,
+ value,
+ onChange,
+}: CalendarEventLocationInputProps) => {
+ const {
+ placeAutocompleteData,
+ getAutocompletePlaceData,
+ closePlaceAutocomplete,
+ resetPlaceAutocomplete,
+ } = usePlaceAutocomplete(CALENDAR_EVENT_LOCATION_AUTOCOMPLETE_DROPDOWN_ID);
+
+ const handleLocationChange = (location: string) => {
+ onChange(location);
+ getAutocompletePlaceData({ address: location });
+ };
+
+ const handlePlaceSelection = (placeId: string) => {
+ const selectedPlace = placeAutocompleteData.find(
+ (place) => place.placeId === placeId,
+ );
+
+ if (!isDefined(selectedPlace)) {
+ return;
+ }
+
+ onChange(selectedPlace.text);
+ resetPlaceAutocomplete();
+ };
+
+ return (
+ <Dropdown
+ dropdownId={CALENDAR_EVENT_LOCATION_AUTOCOMPLETE_DROPDOWN_ID}
+ dropdownPlacement="bottom-start"
+ clickableComponentWidth="100%"
+ disableClickForClickableComponent
+ onClickOutside={closePlaceAutocomplete}
+ clickableComponent={
+ <StyledComposerTextInput
+ type="text"
+ autoComplete="off"
+ aria-label={ariaLabel}
+ placeholder={placeholder}
+ value={value}
+ onChange={(event) => handleLocationChange(event.target.value)}
+ />
+ }
+ dropdownComponents={
+ <PlaceAutocompleteSelect
+ list={placeAutocompleteData}
+ onChange={handlePlaceSelection}
+ dropdownId={CALENDAR_EVENT_LOCATION_AUTOCOMPLETE_DROPDOWN_ID}
+ />
+ }
+ />
+ );
+};
diff --git a/packages/twenty-front/src/modules/activities/calendar/components/__stories__/CalendarEventLocationInput.stories.tsx b/packages/twenty-front/src/modules/activities/calendar/components/__stories__/CalendarEventLocationInput.stories.tsx
new file mode 100644
index 00000000000..41b237d6242
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/calendar/components/__stories__/CalendarEventLocationInput.stories.tsx
@@ -0,0 +1,73 @@
+import { CalendarEventLocationInput } from '@/activities/calendar/components/CalendarEventLocationInput';
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { HttpResponse, delay, graphql } from 'msw';
+import { useState } from 'react';
+import { expect, userEvent, within } from 'storybook/test';
+
+const StatefulCalendarEventLocationInput = () => {
+ const [value, setValue] = useState('');
+
+ return (
+ <CalendarEventLocationInput
+ ariaLabel="Location"
+ placeholder="Add a location"
+ value={value}
+ onChange={setValue}
+ />
+ );
+};
+
+const meta: Meta<typeof CalendarEventLocationInput> = {
+ title: 'Modules/Activities/Calendar/CalendarEventLocationInput',
+ component: CalendarEventLocationInput,
+ render: () => <StatefulCalendarEventLocationInput />,
+ parameters: {
+ msw: {
+ handlers: [
+ graphql.query('GetAutoCompleteAddress', async ({ variables }) => {
+ if (variables.address === 'Paris') {
+ await delay(900);
+
+ return HttpResponse.json({
+ data: {
+ getAutoCompleteAddress: [
+ { text: 'Paris, France', placeId: 'paris' },
+ ],
+ },
+ });
+ }
+
+ return HttpResponse.json({
+ data: {
+ getAutoCompleteAddress: [
+ { text: 'London, United Kingdom', placeId: 'london' },
+ ],
+ },
+ });
+ }),
+ ],
+ },
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof CalendarEventLocationInput>;
+
+export const IgnoresStaleResponses: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const screen = within(canvasElement.ownerDocument.body);
+ const input = canvas.getByRole('textbox', { name: 'Location' });
+
+ await userEvent.type(input, 'Paris');
+ await delay(350);
+ await userEvent.clear(input);
+ await userEvent.type(input, 'London');
+
+ expect(await screen.findByText('London, United Kingdom')).toBeVisible();
+
+ await delay(700);
+
+ expect(screen.queryByText('Paris, France')).not.toBeInTheDocument();
+ },
+};
diff --git a/packages/twenty-front/src/modules/activities/calendar/hooks/__tests__/useCalendarEventComposer.test.ts b/packages/twenty-front/src/modules/activities/calendar/hooks/__tests__/useCalendarEventComposer.test.ts
index 1a701bfca1e..db92d3c0604 100644
--- a/packages/twenty-front/src/modules/activities/calendar/hooks/__tests__/useCalendarEventComposer.test.ts
+++ b/packages/twenty-front/src/modules/activities/calendar/hooks/__tests__/useCalendarEventComposer.test.ts
@@ -95,6 +95,42 @@ describe('useCalendarEventComposer', () => {
expect(onCreated).toHaveBeenCalledTimes(1);
});
+ it('keeps the location controlled and submits the selected value', async () => {
+ mockCreateCalendarEvent.mockResolvedValue(true);
+
+ const { result } = renderHook(() =>
+ useCalendarEventComposer({
+ initialValues: {
+ connectedAccountId: 'account-id',
+ contextRecord: {
+ objectNameSingular: 'person',
+ recordId: 'person-id',
+ },
+ defaultAttendees: '[email protected]',
+ timeZone: 'UTC',
+ },
+ onCreated: jest.fn(),
+ }),
+ );
+
+ act(() => {
+ result.current.setTitle('Planning session');
+ result.current.setLocation('48 Rue de Courcelles, Paris, France');
+ });
+
+ expect(result.current.location).toBe('48 Rue de Courcelles, Paris, France');
+
+ await act(async () => {
+ await result.current.handleCreate();
+ });
+
+ expect(mockCreateCalendarEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ location: '48 Rue de Courcelles, Paris, France',
+ }),
+ );
+ });
+
it('keeps an all-day event at least one day long', () => {
const { result } = renderHook(() =>
useCalendarEventComposer({
diff --git a/packages/twenty-front/src/modules/activities/calendar/hooks/useCalendarEventComposer.ts b/packages/twenty-front/src/modules/activities/calendar/hooks/useCalendarEventComposer.ts
index 4c2ca304eb2..c4478d80bd3 100644
--- a/packages/twenty-front/src/modules/activities/calendar/hooks/useCalendarEventComposer.ts
+++ b/packages/twenty-front/src/modules/activities/calendar/hooks/useCalendarEventComposer.ts
@@ -206,6 +206,7 @@ export const useCalendarEventComposer = ({
hasValidDateRange,
invalidAttendeeEmails,
isFullDay,
+ location,
missingScopes,
selectedAccount,
sendInvitations,
diff --git a/packages/twenty-front/src/modules/geo-map/hooks/usePlaceAutocomplete.ts b/packages/twenty-front/src/modules/geo-map/hooks/usePlaceAutocomplete.ts
new file mode 100644
index 00000000000..fca6b8cb938
--- /dev/null
+++ b/packages/twenty-front/src/modules/geo-map/hooks/usePlaceAutocomplete.ts
@@ -0,0 +1,142 @@
+import { useGetPlaceApiData } from '@/geo-map/hooks/useGetPlaceApiData';
+import { type PlaceAutocompleteResult } from '@/geo-map/types/placeApi';
+import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';
+import { useOpenDropdown } from '@/ui/layout/dropdown/hooks/useOpenDropdown';
+import { isNonEmptyString } from '@sniptt/guards';
+import { atom, useAtomValue, useStore } from 'jotai';
+import { useCallback, useState } from 'react';
+import { isNonEmptyArray } from 'twenty-shared/utils';
+import { useDebouncedCallback } from 'use-debounce';
+import { v4 } from 'uuid';
+
+type GetAutocompletePlaceDataParams = {
+ address: string;
+ country?: string;
+ isFieldCity?: boolean;
+};
+
+type PlaceAutocompleteSession = {
+ tokenForPlaceApi: string | null;
+ latestRequestId: number;
+};
+
+export const usePlaceAutocomplete = (dropdownId: string) => {
+ const [placeAutocompleteData, setPlaceAutocompleteData] = useState<
+ PlaceAutocompleteResult[]
+ >([]);
+ const [placeAutocompleteSessionAtom] = useState(() =>
+ atom<PlaceAutocompleteSession>({
+ tokenForPlaceApi: null,
+ latestRequestId: 0,
+ }),
+ );
+ const placeAutocompleteSession = useAtomValue(placeAutocompleteSessionAtom);
+ const store = useStore();
+
+ const { getPlaceAutocompleteData } = useGetPlaceApiData();
+ const { openDropdown } = useOpenDropdown();
+ const { closeDropdown } = useCloseDropdown();
+
+ const closeDropdownAndClearResults = useCallback(() => {
+ closeDropdown(dropdownId);
+ setPlaceAutocompleteData([]);
+ }, [closeDropdown, dropdownId]);
+
+ const debouncedGetAutocompletePlaceData = useDebouncedCallback(
+ async ({
+ address,
+ country,
+ isFieldCity,
+ requestId,
+ }: GetAutocompletePlaceDataParams & { requestId: number }) => {
+ if (!isNonEmptyString(address.trim())) {
+ closeDropdownAndClearResults();
+ return;
+ }
+
+ const currentSession = store.get(placeAutocompleteSessionAtom);
+ const token = currentSession.tokenForPlaceApi ?? v4();
+
+ if (token !== currentSession.tokenForPlaceApi) {
+ store.set(placeAutocompleteSessionAtom, (latestSession) => ({
+ ...latestSession,
+ tokenForPlaceApi: latestSession.tokenForPlaceApi ?? token,
+ }));
+ }
+
+ const autocompleteData = await getPlaceAutocompleteData(
+ address,
+ token,
+ country,
+ isFieldCity,
+ );
+
+ if (
+ requestId !== store.get(placeAutocompleteSessionAtom).latestRequestId
+ ) {
+ return;
+ }
+
+ if (!isNonEmptyArray(autocompleteData)) {
+ closeDropdownAndClearResults();
+ return;
+ }
+
+ setPlaceAutocompleteData(autocompleteData);
+ openDropdown({
+ dropdownComponentInstanceIdFromProps: dropdownId,
+ });
+ },
+ 300,
+ );
+
+ const getAutocompletePlaceData = useCallback(
+ ({ address, country, isFieldCity }: GetAutocompletePlaceDataParams) => {
+ const currentSession = store.get(placeAutocompleteSessionAtom);
+ const requestId = currentSession.latestRequestId + 1;
+
+ store.set(placeAutocompleteSessionAtom, {
+ ...currentSession,
+ latestRequestId: requestId,
+ });
+
+ return debouncedGetAutocompletePlaceData({
+ address,
+ country,
+ isFieldCity,
+ requestId,
+ });
+ },
+ [debouncedGetAutocompletePlaceData, placeAutocompleteSessionAtom, store],
+ );
+
+ const closePlaceAutocomplete = useCallback(() => {
+ store.set(placeAutocompleteSessionAtom, (currentSession) => ({
+ ...currentSession,
+ latestRequestId: currentSession.latestRequestId + 1,
+ }));
+ debouncedGetAutocompletePlaceData.cancel();
+ closeDropdownAndClearResults();
+ }, [
+ closeDropdownAndClearResults,
+ debouncedGetAutocompletePlaceData,
+ placeAutocompleteSessionAtom,
+ store,
+ ]);
+
+ const resetPlaceAutocomplete = useCallback(() => {
+ store.set(placeAutocompleteSessionAtom, (currentSession) => ({
+ ...currentSession,
+ tokenForPlaceApi: null,
+ }));
+ closePlaceAutocomplete();
+ }, [closePlaceAutocomplete, placeAutocompleteSessionAtom, store]);
+
+ return {
+ placeAutocompleteData,
+ tokenForPlaceApi: placeAutocompleteSession.tokenForPlaceApi,
+ getAutocompletePlaceData,
+ closePlaceAutocomplete,
+ resetPlaceAutocomplete,
+ };
+};
diff --git a/packages/twenty-front/src/modules/ui/field/input/components/AddressInput.tsx b/packages/twenty-front/src/modules/ui/field/input/components/AddressInput.tsx
index 727579e7665..354dcbc28d3 100644
--- a/packages/twenty-front/src/modules/ui/field/input/components/AddressInput.tsx
+++ b/packages/twenty-front/src/modules/ui/field/input/components/AddressInput.tsx
@@ -14,9 +14,8 @@ import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';
import { activeDropdownFocusIdState } from '@/ui/layout/dropdown/states/activeDropdownFocusIdState';
import { useListenClickOutside } from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
-import { isDefined } from 'twenty-shared/utils';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
import { MOBILE_VIEWPORT } from 'twenty-ui/theme-constants';
-import { v4 } from 'uuid';
import { t } from '@lingui/core/macro';
import { type AllowedAddressSubField } from 'twenty-shared/types';
@@ -114,7 +113,6 @@ export const AddressInput = ({
placeAutocompleteData,
tokenForPlaceApi,
typeOfAddressForAutocomplete,
- setTokenForPlaceApi,
setTypeOfAddressForAutocomplete,
getAutocompletePlaceData,
autoFillInputsFromPlaceDetails,
@@ -148,10 +146,6 @@ export const AddressInput = ({
onChange?.(updatedAddress);
if (field === 'addressStreet1' || field === 'addressCity') {
- const token = tokenForPlaceApi ?? v4();
- if (token !== tokenForPlaceApi) {
- setTokenForPlaceApi(token);
- }
const countryCode = findCountryCodeByCountryName(
updatedAddress.addressCountry ?? '',
);
@@ -159,19 +153,16 @@ export const AddressInput = ({
setTypeOfAddressForAutocomplete(field);
}
const isFieldCity = field === 'addressCity';
- getAutocompletePlaceData(
- updatedAddressPart,
- token,
- countryCode,
+ getAutocompletePlaceData({
+ address: updatedAddressPart,
+ country: countryCode,
isFieldCity,
- );
+ });
}
},
[
internalValue,
onChange,
- tokenForPlaceApi,
- setTokenForPlaceApi,
findCountryCodeByCountryName,
typeOfAddressForAutocomplete,
setTypeOfAddressForAutocomplete,
@@ -261,9 +252,7 @@ export const AddressInput = ({
const validAutocompleteData = useMemo(
() =>
- placeAutocompleteData && placeAutocompleteData.length > 0
- ? placeAutocompleteData
- : null,
+ isNonEmptyArray(placeAutocompleteData) ? placeAutocompleteData : null,
[placeAutocompleteData],
);
diff --git a/packages/twenty-front/src/modules/ui/field/input/hooks/__tests__/useAddressAutocomplete.test.tsx b/packages/twenty-front/src/modules/ui/field/input/hooks/__tests__/useAddressAutocomplete.test.tsx
index 65d52c603f4..2019394f334 100644
--- a/packages/twenty-front/src/modules/ui/field/input/hooks/__tests__/useAddressAutocomplete.test.tsx
+++ b/packages/twenty-front/src/modules/ui/field/input/hooks/__tests__/useAddressAutocomplete.test.tsx
@@ -10,7 +10,8 @@ jest.mock('../useCountryUtils');
jest.mock('@/ui/layout/dropdown/hooks/useOpenDropdown');
jest.mock('@/ui/layout/dropdown/hooks/useCloseDropdown');
jest.mock('use-debounce', () => ({
- useDebouncedCallback: (fn: (...args: any[]) => any) => fn,
+ useDebouncedCallback: (fn: (...args: any[]) => any) =>
+ Object.assign(fn, { cancel: () => undefined }),
}));
const mockGetPlaceAutocompleteData = jest.fn();
@@ -58,7 +59,7 @@ describe('useAddressAutocomplete', () => {
const { result } = renderHook(() => useAddressAutocomplete());
await act(async () => {
- await result.current.getAutocompletePlaceData('123 Main', 'token123');
+ await result.current.getAutocompletePlaceData({ address: '123 Main' });
});
expect(mockOpenDropdown).toHaveBeenCalled();
@@ -74,7 +75,9 @@ describe('useAddressAutocomplete', () => {
const { result } = renderHook(() => useAddressAutocomplete());
await act(async () => {
- await result.current.getAutocompletePlaceData('nonexistent', 'token123');
+ await result.current.getAutocompletePlaceData({
+ address: 'nonexistent',
+ });
});
expect(mockCloseDropdown).toHaveBeenCalled();
@@ -86,7 +89,7 @@ describe('useAddressAutocomplete', () => {
const { result } = renderHook(() => useAddressAutocomplete());
await act(async () => {
- await result.current.getAutocompletePlaceData('test', 'token123');
+ await result.current.getAutocompletePlaceData({ address: 'test' });
});
expect(mockCloseDropdown).toHaveBeenCalled();
@@ -245,14 +248,19 @@ describe('useAddressAutocomplete', () => {
it('should set token to null after autofilling', async () => {
const mockOnChange = jest.fn();
mockGetPlaceDetailsData.mockResolvedValue({});
+ mockGetPlaceAutocompleteData.mockResolvedValue([
+ { text: '123 Main St', placeId: 'place123' },
+ ]);
const { result } = renderHook(() => useAddressAutocomplete(mockOnChange));
- act(() => {
- result.current.setTokenForPlaceApi('initial-token');
+ await act(async () => {
+ await result.current.getAutocompletePlaceData({
+ address: '123 Main St',
+ });
});
- expect(result.current.tokenForPlaceApi).toBe('initial-token');
+ expect(result.current.tokenForPlaceApi).not.toBeNull();
await act(async () => {
await result.current.autoFillInputsFromPlaceDetails(
@@ -264,6 +272,26 @@ describe('useAddressAutocomplete', () => {
expect(result.current.tokenForPlaceApi).toBeNull();
});
+ it('reuses the session token before state has rerendered', async () => {
+ mockGetPlaceAutocompleteData.mockResolvedValue([
+ { text: '123 Main St', placeId: 'place123' },
+ ]);
+
+ const { result } = renderHook(() => useAddressAutocomplete());
+
+ await act(async () => {
+ await Promise.all([
+ result.current.getAutocompletePlaceData({ address: '123 Main' }),
+ result.current.getAutocompletePlaceData({ address: '123 Main St' }),
+ ]);
+ });
+
+ const firstToken = mockGetPlaceAutocompleteData.mock.calls[0][1];
+ const secondToken = mockGetPlaceAutocompleteData.mock.calls[1][1];
+
+ expect(firstToken).toBe(secondToken);
+ });
+
it('should handle country code conversion correctly', async () => {
const mockOnChange = jest.fn();
const mockPlaceData = {
@@ -299,17 +327,16 @@ describe('useAddressAutocomplete', () => {
const { result } = renderHook(() => useAddressAutocomplete());
await act(async () => {
- await result.current.getAutocompletePlaceData(
- 'Boston',
- 'token123',
- 'US',
- true,
- );
+ await result.current.getAutocompletePlaceData({
+ address: 'Boston',
+ country: 'US',
+ isFieldCity: true,
+ });
});
expect(mockGetPlaceAutocompleteData).toHaveBeenCalledWith(
'Boston',
- 'token123',
+ expect.any(String),
'US',
true,
);
diff --git a/packages/twenty-front/src/modules/ui/field/input/hooks/useAddressAutocomplete.ts b/packages/twenty-front/src/modules/ui/field/input/hooks/useAddressAutocomplete.ts
index 187bdff2950..0540b7c43b5 100644
--- a/packages/twenty-front/src/modules/ui/field/input/hooks/useAddressAutocomplete.ts
+++ b/packages/twenty-front/src/modules/ui/field/input/hooks/useAddressAutocomplete.ts
@@ -2,72 +2,32 @@ import { useCallback, useState } from 'react';
import { SELECT_AUTOCOMPLETE_LIST_DROPDOWN_ID } from '@/geo-map/constants/SelectAutocompleteListDropDownId';
import { useGetPlaceApiData } from '@/geo-map/hooks/useGetPlaceApiData';
-import { type PlaceAutocompleteResult } from '@/geo-map/types/placeApi';
+import { usePlaceAutocomplete } from '@/geo-map/hooks/usePlaceAutocomplete';
import { type FieldAddressDraftValue } from '@/object-record/record-field/ui/types/FieldInputDraftValue';
-import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';
-import { useOpenDropdown } from '@/ui/layout/dropdown/hooks/useOpenDropdown';
-import { isDefined } from 'twenty-shared/utils';
-import { useDebouncedCallback } from 'use-debounce';
import { useCountryUtils } from './useCountryUtils';
export const useAddressAutocomplete = (
onChange?: (updatedValue: FieldAddressDraftValue) => void,
) => {
- const [placeAutocompleteData, setPlaceAutocompleteData] = useState<
- PlaceAutocompleteResult[] | null
- >([]);
- const [tokenForPlaceApi, setTokenForPlaceApi] = useState<string | null>(null);
const [typeOfAddressForAutocomplete, setTypeOfAddressForAutocomplete] =
useState<string | null>(null);
- const { getPlaceAutocompleteData, getPlaceDetailsData } =
- useGetPlaceApiData();
- const { openDropdown } = useOpenDropdown();
- const { closeDropdown: closeDropdownHook } = useCloseDropdown();
+ const { getPlaceDetailsData } = useGetPlaceApiData();
const { findCountryNameByCountryCode } = useCountryUtils();
- const openDropdownOfAutocomplete = useCallback(() => {
- openDropdown({
- dropdownComponentInstanceIdFromProps:
- SELECT_AUTOCOMPLETE_LIST_DROPDOWN_ID,
- });
- }, [openDropdown]);
+ const {
+ placeAutocompleteData,
+ tokenForPlaceApi,
+ getAutocompletePlaceData,
+ closePlaceAutocomplete,
+ resetPlaceAutocomplete,
+ } = usePlaceAutocomplete(SELECT_AUTOCOMPLETE_LIST_DROPDOWN_ID);
const closeDropdownOfAutocomplete = useCallback(() => {
- closeDropdownHook(SELECT_AUTOCOMPLETE_LIST_DROPDOWN_ID);
- setPlaceAutocompleteData(null);
+ closePlaceAutocomplete();
setTypeOfAddressForAutocomplete(null);
- }, [closeDropdownHook]);
-
- const getAutocompletePlaceData = useDebouncedCallback(
- async (
- address: string,
- token: string,
- country?: string,
- isFieldCity?: boolean,
- ) => {
- const placeAutocompleteData = await getPlaceAutocompleteData(
- address,
- token,
- country,
- isFieldCity,
- );
-
- const newData = placeAutocompleteData?.map((data) => ({
- text: data.text,
- placeId: data.placeId,
- }));
-
- if (isDefined(newData) && newData?.length > 0) {
- openDropdownOfAutocomplete();
- setPlaceAutocompleteData(newData);
- } else {
- closeDropdownOfAutocomplete();
- }
- },
- 300,
- );
+ }, [closePlaceAutocomplete]);
const autoFillInputsFromPlaceDetails = useCallback(
async (
@@ -96,8 +56,8 @@ export const useAddressAutocomplete = (
placeData?.location?.lng ?? internalValue?.addressLng ?? null,
};
- setTokenForPlaceApi(null);
- closeDropdownOfAutocomplete();
+ resetPlaceAutocomplete();
+ setTypeOfAddressForAutocomplete(null);
onChange?.(updatedAddress);
return updatedAddress;
@@ -105,7 +65,7 @@ export const useAddressAutocomplete = (
[
getPlaceDetailsData,
findCountryNameByCountryCode,
- closeDropdownOfAutocomplete,
+ resetPlaceAutocomplete,
onChange,
],
);
@@ -114,7 +74,6 @@ export const useAddressAutocomplete = (
placeAutocompleteData,
tokenForPlaceApi,
typeOfAddressForAutocomplete,
- setTokenForPlaceApi,
setTypeOfAddressForAutocomplete,
getAutocompletePlaceData,
autoFillInputsFromPlaceDetails,