From 64e5860aa8a4f8999cc5b507a508d07b0c285700 Mon Sep 17 00:00:00 2001 From: Denis Vershkov Date: Thu, 8 Feb 2024 20:04:23 +0300 Subject: [PATCH] fix(Select): do not call onFilterChange on mount (#1326) --- src/components/Select/Select.tsx | 34 ++++++++++++------- .../Select/__tests__/Select.filter.test.tsx | 2 +- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/src/components/Select/Select.tsx b/src/components/Select/Select.tsx index 6613e9358c..731a13d6f0 100644 --- a/src/components/Select/Select.tsx +++ b/src/components/Select/Select.tsx @@ -98,6 +98,26 @@ export const Select = React.forwardRef(function const filterRef = React.useRef(null); const listRef = React.useRef>(null); const handleControlRef = useForkRef(ref, controlRef); + + const handleFilterChange = React.useCallback( + (nextFilter: string) => { + onFilterChange?.(nextFilter); + dispatch({type: 'SET_FILTER', payload: {filter: nextFilter}}); + }, + [onFilterChange], + ); + + const handleOpenChange = React.useCallback( + (open: boolean) => { + onOpenChange?.(open); + + if (!open && filterable) { + handleFilterChange(''); + } + }, + [filterable, onOpenChange, handleFilterChange], + ); + const { value, open, @@ -114,7 +134,7 @@ export const Select = React.forwardRef(function multiple, open: propsOpen, onClose, - onOpenChange, + onOpenChange: handleOpenChange, }); const uniqId = useUniqId(); const selectId = id ?? uniqId; @@ -197,14 +217,6 @@ export const Select = React.forwardRef(function listRef?.current?.onKeyDown(e); }, []); - const handleFilterChange = React.useCallback( - (nextFilter: string) => { - onFilterChange?.(nextFilter); - dispatch({type: 'SET_FILTER', payload: {filter: nextFilter}}); - }, - [onFilterChange], - ); - const handleQuickSearchChange = React.useCallback((search: string) => { if (search) { const itemIndex = findItemIndexByQuickSearch(search, getListItems(listRef)); @@ -228,10 +240,8 @@ export const Select = React.forwardRef(function if (filterable) { filterRef.current?.focus(); } - } else { - handleFilterChange(''); } - }, [open, filterable, handleFilterChange]); + }, [open, filterable]); const mods: CnMods = { ...(width === 'max' && {width}), diff --git a/src/components/Select/__tests__/Select.filter.test.tsx b/src/components/Select/__tests__/Select.filter.test.tsx index 0fe29dc832..8d31e0fc80 100644 --- a/src/components/Select/__tests__/Select.filter.test.tsx +++ b/src/components/Select/__tests__/Select.filter.test.tsx @@ -68,7 +68,7 @@ describe('Select filter', () => { await user.keyboard('1'); // empty expect(queryAllByRole('option').length).toBe(0); - expect(onFilterChange).toBeCalledTimes(4); + expect(onFilterChange).toBeCalledTimes(3); }); test('should render node with renderEmptyOptions', async () => {