-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
Copy pathuseReferenceManyFieldController.ts
217 lines (207 loc) · 6.6 KB
/
useReferenceManyFieldController.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import { useCallback, useEffect, useRef } from 'react';
import get from 'lodash/get';
import isEqual from 'lodash/isEqual';
import { useSafeSetState, removeEmpty } from '../../util';
import { useGetManyReference } from '../../dataProvider';
import { useNotify } from '../../notification';
import { Identifier, RaRecord, SortPayload } from '../../types';
import { ListControllerResult } from '../list';
import usePaginationState from '../usePaginationState';
import { useRecordSelection } from '../list/useRecordSelection';
import useSortState from '../useSortState';
import { useResourceContext } from '../../core';
export interface UseReferenceManyFieldControllerParams<
RecordType extends RaRecord = RaRecord
> {
filter?: any;
page?: number;
perPage?: number;
record?: RecordType;
reference: string;
resource?: string;
sort?: SortPayload;
source?: string;
target: string;
}
const defaultFilter = {};
/**
* Fetch reference records, and return them when available
*
* Uses dataProvider.getManyReference() internally.
*
* @example // fetch the comments related to the current post
* const { isLoading, data } = useReferenceManyFieldController({
* reference: 'comments',
* target: 'post_id',
* record: { id: 123, title: 'hello, world' },
* resource: 'posts',
* });
*
* @param {Object} props
* @param {string} props.reference The linked resource name. Required.
* @param {string} props.target The target resource key. Required.
* @param {Object} props.filter The filter applied on the recorded records list
* @param {number} props.page the page number
* @param {number} props.perPage the number of item per page
* @param {Object} props.record The current resource record
* @param {string} props.resource The current resource name
* @param {Object} props.sort the sort to apply to the referenced records
* @param {string} props.source The key of the linked resource identifier
*
* @returns {ListControllerResult} The reference many props
*/
export const useReferenceManyFieldController = <
RecordType extends RaRecord = RaRecord,
ReferenceRecordType extends RaRecord = RaRecord
>(
props: UseReferenceManyFieldControllerParams<RecordType>
): ListControllerResult<ReferenceRecordType> => {
const {
reference,
record,
target,
filter = defaultFilter,
source,
page: initialPage,
perPage: initialPerPage,
sort: initialSort = { field: 'id', order: 'DESC' },
} = props;
const notify = useNotify();
const resource = useResourceContext(props);
// pagination logic
const { page, setPage, perPage, setPerPage } = usePaginationState({
page: initialPage,
perPage: initialPerPage,
});
// sort logic
const { sort, setSort: setSortState } = useSortState(initialSort);
const setSort = useCallback(
(sort: SortPayload) => {
setSortState(sort);
setPage(1);
},
[setPage, setSortState]
);
// selection logic
const [selectedIds, selectionModifiers] = useRecordSelection(
`${resource}.${record?.id}.${reference}`
);
// filter logic
const filterRef = useRef(filter);
const [displayedFilters, setDisplayedFilters] = useSafeSetState<{
[key: string]: boolean;
}>({});
const [filterValues, setFilterValues] = useSafeSetState<{
[key: string]: any;
}>(filter);
const hideFilter = useCallback(
(filterName: string) => {
setDisplayedFilters(previousState => {
const { [filterName]: _, ...newState } = previousState;
return newState;
});
setFilterValues(previousState => {
const { [filterName]: _, ...newState } = previousState;
return newState;
});
},
[setDisplayedFilters, setFilterValues]
);
const showFilter = useCallback(
(filterName: string, defaultValue: any) => {
setDisplayedFilters(previousState => ({
...previousState,
[filterName]: true,
}));
setFilterValues(previousState => ({
...previousState,
[filterName]: defaultValue,
}));
},
[setDisplayedFilters, setFilterValues]
);
const setFilters = useCallback(
(filters, displayedFilters) => {
setFilterValues(removeEmpty(filters));
setDisplayedFilters(displayedFilters);
setPage(1);
},
[setDisplayedFilters, setFilterValues, setPage]
);
// handle filter prop change
useEffect(() => {
if (!isEqual(filter, filterRef.current)) {
filterRef.current = filter;
setFilterValues(filter);
}
});
const {
data,
total,
pageInfo,
error,
isFetching,
isLoading,
refetch,
} = useGetManyReference<ReferenceRecordType>(
reference,
{
target,
id: get(record, source) as Identifier,
pagination: { page, perPage },
sort,
filter: filterValues,
},
{
keepPreviousData: true,
onError: error =>
notify(
typeof error === 'string'
? error
: error.message || 'ra.notification.http_error',
{
type: 'error',
messageArgs: {
_:
typeof error === 'string'
? error
: error && error.message
? error.message
: undefined,
},
}
),
}
);
return {
sort,
data,
defaultTitle: null,
displayedFilters,
error,
filterValues,
hideFilter,
isFetching,
isLoading,
onSelect: selectionModifiers.select,
onToggleItem: selectionModifiers.toggle,
onUnselectItems: selectionModifiers.clearSelection,
page,
perPage,
refetch,
resource: reference,
selectedIds,
setFilters,
setPage,
setPerPage,
hasNextPage: pageInfo
? pageInfo.hasNextPage
: total != null
? page * perPage < total
: undefined,
hasPreviousPage: pageInfo ? pageInfo.hasPreviousPage : page > 1,
setSort,
showFilter,
total,
};
};