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

Fix AutocompleteArrayInput shows undefined on blur #8331

Merged
merged 1 commit into from
Oct 28, 2022
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
53 changes: 28 additions & 25 deletions docs/AutocompleteArrayInput.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ The list of choices must be an array of objects - one object for each possible c
]} />
```

You can also use an array of objects with different properties for the label and value, given you specify the `optionText` and `optionValue` props:
You can also use an array of objects with different properties for the label and value, given you specify the [`optionText`](#optiontext) and [`optionValue`](#optionvalue) props:

```jsx
<AutocompleteArrayInput source="roles" choices={[
Expand Down Expand Up @@ -129,60 +129,61 @@ const choices = possibleValues.map(value => ({ id: value, name: ucfirst(value) }

## `create`

To allow users to add new options, pass a React element as the `create` prop. `<AutocompleteArrayInput>` will then render a menu item at the bottom of the list, which will render the passed element when clicked.
To allow users to add new options, pass a React element as the `create` prop. `<AutocompleteArrayInput>` will then render a "Create" option at the bottom of the choices list. When clicked, it will render the create element.

![create option](./img/autocomplete-array-input-create.gif)

{% raw %}
```jsx
import { CreateCategory } from './CreateCategory';
import { CreateRole } from './CreateRole';

const choices = [
{ id: 'admin', name: 'Admin' },
{ id: 'u001', name: 'Editor' },
{ id: 'u002', name: 'Moderator' },
{ id: 'u003', name: 'Reviewer' },
];

const PostCreate = () => (
const UserCreate = () => (
<Create>
<SimpleForm>
<TextInput source="title" />
<ReferenceArrayInput source="category_ids" reference="categories">
<AutocompleteArrayInput create={<CreateCategory />} />
</ReferenceArrayInput>
<SelectArrayInput
source="roles"
choices={choices}
create={<CreateRole />}
/>
</SimpleForm>
</Create>
);

// in ./CreateCategory.js
import { useCreate, useCreateSuggestionContext } from 'react-admin';
// in ./CreateRole.js
import { useCreateSuggestionContext } from 'react-admin';
import {
Box,
BoxProps,
Button,
Dialog,
DialogActions,
DialogContent,
TextField,
} from '@mui/material';

const CreateCategory = () => {
const CreateRole = () => {
const { filter, onCancel, onCreate } = useCreateSuggestionContext();
const [create] = useCreate();
const [value, setValue] = React.useState(filter || '');

const handleSubmit = event => {
event.preventDefault();
create(
'categories',
{ data: { title: value } },
{
onSuccess: (data) => {
setValue('');
onCreate(data);
},
}
);
const newOption = { id: value, name: value };
choices.push(newOption);
setValue('');
onCreate(newOption);
};

return (
<Dialog open onClose={onCancel}>
<form onSubmit={handleSubmit}>
<DialogContent>
<TextField
label="New category name"
label="Role name"
value={value}
onChange={event => setValue(event.target.value)}
autoFocus
Expand All @@ -201,6 +202,8 @@ const CreateCategory = () => {

If you just need to ask users for a single string to create the new option, you can use [the `onCreate` prop](#oncreate) instead.

If you're in a `<ReferenceArrayInput>` or `<ReferenceManyToManyInput>`, the `handleSubmit` will need to create a new record in the related resource. Check the [Creating New Choices](#creating-new-choices) for an example.

## `debounce`

When used inside a [`<ReferenceArrayInput>`](./ReferenceArrayInput.md), `<AutocompleteArrayInput>` will call `dataProvider.getList()` with the current input value as filter after a delay of 250ms. This is to avoid calling the API too often while users are typing their query.
Expand Down
Binary file added docs/img/autocomplete-array-input-create.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,64 @@ export const Basic = () => (
</AdminContext>
);

const choices = [
{ id: 'admin', name: 'Admin' },
{ id: 'u001', name: 'Editor' },
{ id: 'u002', name: 'Moderator' },
{ id: 'u003', name: 'Reviewer' },
];

const CreateRole = () => {
const { filter, onCancel, onCreate } = useCreateSuggestionContext();
const [value, setValue] = React.useState(filter || '');

const handleSubmit = event => {
event.preventDefault();
const newOption = { id: value, name: value };
choices.push(newOption);
setValue('');
onCreate(newOption);
};

return (
<Dialog open onClose={onCancel}>
<form onSubmit={handleSubmit}>
<DialogContent>
<TextField
label="Role name"
value={value}
onChange={event => setValue(event.target.value)}
autoFocus
/>
</DialogContent>
<DialogActions>
<Button type="submit">Save</Button>
<Button onClick={onCancel}>Cancel</Button>
</DialogActions>
</form>
</Dialog>
);
};

export const CreateProp = () => (
<AdminContext i18nProvider={i18nProvider}>
<Create
resource="users"
record={{ roles: ['u001', 'u003'] }}
sx={{ width: 600 }}
>
<SimpleForm>
<AutocompleteArrayInput
source="roles"
choices={choices}
sx={{ width: 400 }}
create={<CreateRole />}
/>
</SimpleForm>
</Create>
</AdminContext>
);

const dataProvider = {
getOne: (resource, params) =>
Promise.resolve({
Expand Down
3 changes: 2 additions & 1 deletion packages/ra-ui-materialui/src/input/AutocompleteInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ If you provided a React element for the optionText prop, you must also provide t
);

const finalOnBlur = useCallback((): void => {
if (clearOnBlur) {
if (clearOnBlur && !multiple) {
const optionLabel = getOptionLabel(selectedChoice);
if (!isEqual(optionLabel, filterValue)) {
setFilterValue(optionLabel);
Expand All @@ -422,6 +422,7 @@ If you provided a React element for the optionText prop, you must also provide t
selectedChoice,
filterValue,
debouncedSetFilter,
multiple,
]);

useEffect(() => {
Expand Down