Skip to content

Commit 44406e2

Browse files
committedFeb 9, 2021
Fix selection and tests
1 parent 2ffbe54 commit 44406e2

File tree

1 file changed

+32
-15
lines changed

1 file changed

+32
-15
lines changed
 

‎packages/ra-core/src/controller/input/useReferenceArrayInputController.ts

+32-15
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,15 @@ import {
99
Record,
1010
SortPayload,
1111
ReduxState,
12+
Identifier,
1213
} from '../../types';
1314
import { useGetMany } from '../../dataProvider';
1415
import { FieldInputProps, useForm } from 'react-final-form';
1516
import useGetMatching from '../../dataProvider/useGetMatching';
1617
import { useTranslate } from '../../i18n';
1718
import { getStatusForArrayInput as getDataStatus } from './referenceDataStatus';
1819
import { useResourceContext } from '../../core';
19-
import { usePaginationState, useSelectionState, useSortState } from '..';
20+
import { usePaginationState, useSortState } from '..';
2021
import { ListControllerProps } from '../useListController';
2122
import { indexById, removeEmpty, useSafeSetState } from '../../util';
2223
import { SORT_DESC } from '../../reducer/admin/resource/list/queryReducer';
@@ -126,20 +127,36 @@ const useReferenceArrayInputController = (
126127
perPage: initialPerPage,
127128
});
128129

129-
// selection logic
130-
const {
131-
selectedIds,
132-
onSelect,
133-
onToggleItem,
134-
onUnselectItems,
135-
} = useSelectionState(input.value);
136-
137130
const form = useForm();
138-
useEffect(() => {
139-
if (!isEqual(input.value, selectedIds)) {
140-
form.change(input.name, selectedIds);
141-
}
142-
}, [input.name, input.value, selectedIds, form]);
131+
const onSelect = useCallback(
132+
(newIds: Identifier[]) => {
133+
const newValue = new Set(input.value);
134+
newIds.forEach(newId => {
135+
newValue.add(newId);
136+
});
137+
138+
form.change(input.name, Array.from(newValue));
139+
},
140+
[form, input.name, input.value]
141+
);
142+
143+
const onUnselectItems = useCallback(() => {
144+
form.change(input.name, []);
145+
}, [form, input.name]);
146+
147+
const onToggleItem = useCallback(
148+
(id: Identifier) => {
149+
if (input.value.contains(id)) {
150+
form.change(
151+
input.name,
152+
input.value.filter(selectedId => selectedId !== id)
153+
);
154+
} else {
155+
form.change(input.name, [...input.value, id]);
156+
}
157+
},
158+
[form, input.name, input.value]
159+
);
143160

144161
// sort logic
145162
const sortRef = useRef(initialSort);
@@ -296,7 +313,7 @@ const useReferenceArrayInputController = (
296313
page,
297314
perPage,
298315
resource,
299-
selectedIds,
316+
selectedIds: input.value,
300317
setFilter,
301318
setFilters,
302319
setPage,

0 commit comments

Comments
 (0)