From cc044947aa2d275e5b50c311e705ad96a49add4c Mon Sep 17 00:00:00 2001 From: adrien guernier Date: Fri, 19 Jul 2024 15:30:16 +0200 Subject: [PATCH] fix clear button does not clear new choice --- .../src/input/AutocompleteInput.spec.tsx | 16 +++++++++++++++ .../src/input/AutocompleteInput.tsx | 20 +++++++++++-------- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/packages/ra-ui-materialui/src/input/AutocompleteInput.spec.tsx b/packages/ra-ui-materialui/src/input/AutocompleteInput.spec.tsx index 42a3ca97794..43255b37d6d 100644 --- a/packages/ra-ui-materialui/src/input/AutocompleteInput.spec.tsx +++ b/packages/ra-ui-materialui/src/input/AutocompleteInput.spec.tsx @@ -25,6 +25,7 @@ import { OnChange, InsideReferenceInputOnChange, WithInputProps, + OnCreate, } from './AutocompleteInput.stories'; import { ReferenceArrayInput } from './ReferenceArrayInput'; import { AutocompleteArrayInput } from './AutocompleteArrayInput'; @@ -1687,6 +1688,21 @@ describe('', () => { }); }); + it('should clear the input mutiple tiles with on create set', async () => { + render(); + + const input = (await screen.findByLabelText( + 'Author' + )) as HTMLInputElement; + userEvent.type(input, 'New choice'); + const clear = screen.getByLabelText('Clear value'); + fireEvent.click(clear); + expect(input.value).toEqual(''); + userEvent.type(input, 'New choice'); + fireEvent.click(clear); + expect(input.value).toEqual(''); + }); + it('should handle nullish values', async () => { render(); diff --git a/packages/ra-ui-materialui/src/input/AutocompleteInput.tsx b/packages/ra-ui-materialui/src/input/AutocompleteInput.tsx index 88910a97f75..008a4d52daf 100644 --- a/packages/ra-ui-materialui/src/input/AutocompleteInput.tsx +++ b/packages/ra-ui-materialui/src/input/AutocompleteInput.tsx @@ -468,7 +468,10 @@ If you provided a React element for the optionText prop, you must also provide t setFilterValue(newInputValue); debouncedSetFilter(newInputValue); } - + if (reason === 'clear') { + setFilterValue(''); + debouncedSetFilter(''); + } onInputChange?.(event, newInputValue, reason); }; @@ -524,13 +527,14 @@ If you provided a React element for the optionText prop, you must also provide t return filteredOptions; }; - const handleAutocompleteChange = ( - event: any, - newValue: any, - _reason: string - ) => { - handleChangeWithCreateSupport(newValue != null ? newValue : emptyValue); - }; + const handleAutocompleteChange = useCallback( + (event: any, newValue: any, _reason: string) => { + handleChangeWithCreateSupport( + newValue != null ? newValue : emptyValue + ); + }, + [emptyValue, handleChangeWithCreateSupport] + ); const oneSecondHasPassed = useTimeout(1000, filterValue);