Skip to content

refactor: Omnichannel's unit autocompletes to useInfiniteQuery #35875

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 7 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 0 additions & 74 deletions apps/meteor/client/components/Omnichannel/hooks/useUnitsList.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import type { IOmnichannelBusinessUnit, Serialized } from '@rocket.chat/core-typings';
import { useEndpoint } from '@rocket.chat/ui-contexts';
import { useInfiniteQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';

type UnitsListOptions = {
text: string;
haveNone?: boolean;
limit?: number;
};

export type UnitOption = {
_id: string;
value: string;
label: string;
};

const DEFAULT_QUERY_LIMIT = 25;

export const useUnitsList = (options: UnitsListOptions) => {
const { t } = useTranslation();
const { haveNone = false, text, limit = DEFAULT_QUERY_LIMIT } = options;
const getUnits = useEndpoint('GET', '/v1/livechat/units');

const formatUnitItem = (u: Serialized<IOmnichannelBusinessUnit>): UnitOption => ({
_id: u._id,
label: u.name,
value: u._id,
});

return useInfiniteQuery({
queryKey: ['/v1/livechat/units', options],
queryFn: async ({ pageParam: offset = 0 }) => {
const { units, ...data } = await getUnits({
...(text && { text }),
offset,
count: limit,
sort: `{ "name": 1 }`,
});

return {
...data,
units: units.map(formatUnitItem),
};
},
select: (data) => {
const items = data.pages.flatMap<UnitOption>((page) => page.units);

haveNone &&
items.unshift({
_id: '',
label: t('None'),
value: '',
});

return items;
},
initialPageParam: 0,
getNextPageParam: (lastPage) => {
const offset = lastPage.offset + lastPage.count;
return offset < lastPage.total ? offset : undefined;
},
initialData: () => ({
pages: [{ units: [], offset: 0, count: 0, total: Infinity }],
pageParams: [0],
}),
});
};
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
import { PaginatedSelectFiltered } from '@rocket.chat/fuselage';
import { useDebouncedValue, useEffectEvent } from '@rocket.chat/fuselage-hooks';
import { useEffect, useMemo, useState } from 'react';
import type { ComponentProps } from 'react';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';

import type { UnitOption } from '../../components/Omnichannel/hooks/useUnitsList';
import { useUnitsList } from '../../components/Omnichannel/hooks/useUnitsList';
import { useRecordList } from '../../hooks/lists/useRecordList';
import { AsyncStatePhase } from '../../lib/asyncState';
import type { RecordList } from '../../lib/lists/RecordList';

type AutoCompleteUnitProps = {
id?: string;
disabled?: boolean;
value: string | undefined;
error?: string;
placeholder?: string;
type AutoCompleteUnitProps = Omit<
ComponentProps<typeof PaginatedSelectFiltered>,
'filter' | 'setFilter' | 'options' | 'endReached' | 'renderItem'
> & {
haveNone?: boolean;
value: string | undefined;
onChange: (value: string) => void;
onLoadItems?: (list: RecordList<UnitOption>) => void;
onLoadItems?: (list: UnitOption[]) => void;
};

const AutoCompleteUnit = ({
Expand All @@ -35,16 +32,13 @@ const AutoCompleteUnit = ({

const debouncedUnitFilter = useDebouncedValue(unitsFilter, 500);

const { itemsList, loadMoreItems: loadMoreUnits } = useUnitsList(
useMemo(() => ({ text: debouncedUnitFilter, haveNone }), [debouncedUnitFilter, haveNone]),
);
const { phase: unitsPhase, itemCount: unitsTotal, items: unitsList } = useRecordList(itemsList);
const { data: unitsList, fetchNextPage } = useUnitsList({ text: debouncedUnitFilter, haveNone });

const handleLoadItems = useEffectEvent(onLoadItems);

useEffect(() => {
handleLoadItems(itemsList);
}, [handleLoadItems, unitsTotal, itemsList]);
handleLoadItems(unitsList);
}, [handleLoadItems, unitsList]);
Comment on lines +40 to +41
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Potential Issues high

useEffect(() => {
		if (Array.isArray(unitsList)) {
			handleLoadItems(unitsList);
		}
	}, [handleLoadItems, unitsList]);

The useEffect hook calls handleLoadItems(unitsList) without checking if unitsList is a valid array, which could lead to unexpected behavior or errors if unitsList is undefined.

This issue appears in multiple locations:

  • apps/meteor/client/omnichannel/additionalForms/AutoCompleteUnit.tsx: Lines 40-41
  • apps/meteor/client/omnichannel/additionalForms/AutoCompleteUnit.tsx: Lines 40-41
  • apps/meteor/client/omnichannel/additionalForms/AutoCompleteUnit.tsx: Lines 40-41
    Please add a check to ensure unitsList is a valid array before invoking the handleLoadItems callback.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.


return (
<PaginatedSelectFiltered
Expand All @@ -61,9 +55,7 @@ const AutoCompleteUnit = ({
setFilter={setUnitsFilter as (value: string | number | undefined) => void}
value={value}
width='100%'
endReached={
unitsPhase === AsyncStatePhase.LOADING ? (): void => undefined : (start): void => loadMoreUnits(start, Math.min(50, unitsTotal))
}
endReached={() => fetchNextPage()}
/>
);
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,49 +1,37 @@
import type { PaginatedMultiSelectOption } from '@rocket.chat/fuselage';
import { PaginatedMultiSelectFiltered } from '@rocket.chat/fuselage';
import { useDebouncedValue } from '@rocket.chat/fuselage-hooks';
import type { ReactElement } from 'react';
import { memo, useMemo, useState } from 'react';
import type { ComponentProps, ReactElement } from 'react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { useUnitsList } from '../../components/Omnichannel/hooks/useUnitsList';
import { useRecordList } from '../../hooks/lists/useRecordList';
import { AsyncStatePhase } from '../../lib/asyncState';

type AutoCompleteUnitsProps = {
value?: PaginatedMultiSelectOption[];
error?: boolean;
placeholder?: string;
onChange: (value: PaginatedMultiSelectOption[]) => void;
};
type AutoCompleteUnitsProps = Omit<
ComponentProps<typeof PaginatedMultiSelectFiltered>,
'filter' | 'setFilter' | 'options' | 'endReached' | 'renderItem'
>;

const AutoCompleteUnits = ({ value, error, placeholder, onChange }: AutoCompleteUnitsProps): ReactElement => {
const AutoCompleteUnits = ({ value, placeholder, onChange, ...props }: AutoCompleteUnitsProps): ReactElement => {
const { t } = useTranslation();
const [unitsFilter, setUnitsFilter] = useState<string>('');

const debouncedUnitFilter = useDebouncedValue(unitsFilter, 500);

const { itemsList: unitsList, loadMoreItems: loadMoreUnits } = useUnitsList(
useMemo(() => ({ text: debouncedUnitFilter }), [debouncedUnitFilter]),
);

const { phase: unitsPhase, itemCount: unitsTotal, items: unitItems } = useRecordList(unitsList);
const { data: unitItems, fetchNextPage } = useUnitsList({ text: debouncedUnitFilter });

return (
<PaginatedMultiSelectFiltered
{...props}
value={value}
error={error}
placeholder={placeholder || t('Select_an_option')}
onChange={onChange}
filter={unitsFilter}
width='100%'
flexShrink={0}
flexGrow={0}
setFilter={setUnitsFilter as (value: string | number | undefined) => void}
options={unitItems}
data-qa='autocomplete-multiple-unit'
endReached={
unitsPhase === AsyncStatePhase.LOADING ? (): void => undefined : (start): void => loadMoreUnits(start!, Math.min(50, unitsTotal))
}
onChange={onChange}
endReached={() => fetchNextPage()}
/>
);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ function EditDepartment({ data, id, title, allowedToForwardData }: EditDepartmen
onChange={onChange}
onLoadItems={(list) => {
// NOTE: list.itemCount > 1 to account for the "None" option
setUnitRequired(!canManageUnits && list.itemCount > 1);
setUnitRequired(!canManageUnits && list.length > 1);
}}
/>
)}
Expand Down
Loading