Skip to content
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

Make SelectArrayInput more resilient #8601

Merged
merged 2 commits into from
Jan 27, 2023
Merged
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
14 changes: 14 additions & 0 deletions packages/ra-ui-materialui/src/input/SelectArrayInput.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -608,4 +608,18 @@ describe('<SelectArrayInput />', () => {
})
).toBeNull();
});

it('should not crash if its value is not an array', () => {
render(
<AdminContext dataProvider={testDataProvider()}>
<SimpleForm
onSubmit={jest.fn()}
defaultValues={{ categories: 1 }}
>
<SelectArrayInput {...defaultProps} />
</SimpleForm>
</AdminContext>
);
expect(screen.queryByTestId('selectArray')).toBeDefined();
});
});
11 changes: 9 additions & 2 deletions packages/ra-ui-materialui/src/input/SelectArrayInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,13 @@ export const SelectArrayInput = (props: SelectArrayInputProps) => {
);
}

// Here wen ensure we always have an array and this array does not contain the default value (empty string)
const finalValue = Array.isArray(field.value ?? [])
? field.value
: field.value
? [field.value]
: [];

return (
<>
<StyledFormControl
Expand All @@ -273,7 +280,7 @@ export const SelectArrayInput = (props: SelectArrayInputProps) => {
}
renderValue={(selected: any[]) => (
<div className={SelectArrayInputClasses.chips}>
{selected
{(Array.isArray(selected) ? selected : [])
.map(item =>
(allChoices || []).find(
// eslint-disable-next-line eqeqeq
Expand All @@ -296,7 +303,7 @@ export const SelectArrayInput = (props: SelectArrayInputProps) => {
{...field}
{...options}
onChange={handleChangeWithCreateSupport}
value={field.value || []}
value={finalValue}
>
{finalChoices.map(renderMenuItem)}
</Select>
Expand Down