Skip to content

Commit

Permalink
Fix unnecessary AutocompleteArrayInput filter reset
Browse files Browse the repository at this point in the history
  • Loading branch information
Kmaschta committed Apr 7, 2020
1 parent 6ef44eb commit b16e8c9
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,43 @@ describe('<AutocompleteArrayInput />', () => {
formApi.change('tags', ['p']);
await waitForDomChange();
expect(setFilter).toHaveBeenCalledTimes(3);
expect(setFilter).toHaveBeenCalledWith('');
});

it('should reset filter only when needed, even if the value is an array of objects (fixes #4454)', async () => {
const setFilter = jest.fn();
let formApi;
const { getByLabelText } = render(
<Form
onSubmit={jest.fn()}
initialValues={{ tags: [{ id: 't' }] }}
render={({ form }) => {
formApi = form;
return (
<AutocompleteArrayInput
{...defaultProps}
choices={[
{ id: 't', name: 'Technical' },
{ id: 'p', name: 'Programming' },
]}
parse={value =>
value && value.map(v => ({ id: v }))
}
format={value => value && value.map(v => v.id)}
setFilter={setFilter}
/>
);
}}
/>
);
const input = getByLabelText('resources.posts.fields.tags');
fireEvent.change(input, { target: { value: 'p' } });
expect(setFilter).toHaveBeenCalledTimes(2);
expect(setFilter).toHaveBeenCalledWith('p');
formApi.change('tags', ['p']);
await waitForDomChange();
expect(setFilter).toHaveBeenCalledTimes(3);
expect(setFilter).toHaveBeenCalledWith('');
});

it('should allow customized rendering of suggesting item', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ const AutocompleteArrayInput: FunctionComponent<
...rest,
});

const values = input.value || [];

const [filterValue, setFilterValue] = React.useState('');

const getSuggestionFromValue = useCallback(
Expand All @@ -176,7 +178,7 @@ const AutocompleteArrayInput: FunctionComponent<

const selectedItems = useMemo(
() => (input.value || []).map(getSuggestionFromValue),
[input.value, getSuggestionFromValue]
[getSuggestionFromValue, input.value]
);

const { getChoiceText, getChoiceValue, getSuggestions } = useSuggestions({
Expand Down Expand Up @@ -215,7 +217,7 @@ const AutocompleteArrayInput: FunctionComponent<
// would have to first clear the input before seeing any other choices
useEffect(() => {
handleFilterChange('');
}, [input.value, handleFilterChange]);
}, [...values, handleFilterChange]);

const handleKeyDown = useCallback(
(event: React.KeyboardEvent) => {
Expand Down

0 comments on commit b16e8c9

Please sign in to comment.