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

Introduce useList #6321

Merged
merged 4 commits into from
Jun 21, 2021
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
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ describe('<ReferenceArrayFieldController />', () => {
});
});

it('should filter string data based on the filter props', () => {
it('should filter string data based on the filter props', async () => {
const children = jest.fn().mockReturnValue('child');
renderWithRedux(
<ReferenceArrayFieldController
Expand All @@ -225,20 +225,24 @@ describe('<ReferenceArrayFieldController />', () => {
},
}
);
expect(children.mock.calls[0][0]).toMatchObject({
basePath: '/bar',
currentSort: { field: 'id', order: 'ASC' },
loaded: true,
loading: true,
data: {
2: { id: 2, title: 'world' },
},
ids: [1, 2],
error: null,
await waitFor(() => {
expect(children).toHaveBeenCalledWith(
expect.objectContaining({
basePath: '/bar',
currentSort: { field: 'id', order: 'ASC' },
loaded: true,
loading: true,
data: {
2: { id: 2, title: 'world' },
},
ids: [2],
error: null,
})
);
});
});

it('should filter array data based on the filter props', () => {
it('should filter array data based on the filter props', async () => {
const children = jest.fn().mockReturnValue('child');
renderWithRedux(
<ReferenceArrayFieldController
Expand All @@ -265,18 +269,22 @@ describe('<ReferenceArrayFieldController />', () => {
},
}
);
expect(children.mock.calls[0][0]).toMatchObject({
basePath: '/bar',
currentSort: { field: 'id', order: 'ASC' },
loaded: true,
loading: true,
data: {
1: { id: 1, items: ['one', 'two'] },
3: { id: 3, items: 'four' },
4: { id: 4, items: ['five'] },
},
ids: [1, 2, 3, 4],
error: null,
await waitFor(() => {
expect(children).toHaveBeenCalledWith(
expect.objectContaining({
basePath: '/bar',
currentSort: { field: 'id', order: 'ASC' },
loaded: true,
loading: true,
data: {
1: { id: 1, items: ['one', 'two'] },
3: { id: 3, items: 'four' },
4: { id: 4, items: ['five'] },
},
ids: [1, 3, 4],
error: null,
})
);
});
});
});
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
import { useCallback, useEffect, useRef } from 'react';
import get from 'lodash/get';
import isEqual from 'lodash/isEqual';

import { useSafeSetState, removeEmpty } from '../../util';
import { Record, RecordMap, Identifier, SortPayload } from '../../types';
import { Record, SortPayload } from '../../types';
import { useGetMany } from '../../dataProvider';
import { ListControllerProps } from '../useListController';
import { useNotify } from '../../sideEffect';
import usePaginationState from '../usePaginationState';
import useSelectionState from '../useSelectionState';
import useSortState from '../useSortState';
import { useResourceContext } from '../../core';
import { indexById } from '../../util/indexById';
import { useList } from '../useList';

interface Option {
basePath?: string;
Expand Down Expand Up @@ -92,173 +86,27 @@ const useReferenceArrayFieldController = (
}
);

const [loadingState, setLoadingState] = useSafeSetState<boolean>(loading);
const [loadedState, setLoadedState] = useSafeSetState<boolean>(loaded);

const [finalData, setFinalData] = useSafeSetState<RecordMap>(
indexById(data)
);
const [finalIds, setFinalIds] = useSafeSetState<Identifier[]>(ids);

// pagination logic
const { page, setPage, perPage, setPerPage } = usePaginationState({
page: initialPage,
perPage: initialPerPage,
});

// sort logic
const { sort, setSort: setSortObject } = useSortState(initialSort);
const setSort = useCallback(
(field: string, order: string = 'ASC') => {
setSortObject({ field, order });
setPage(1);
},
[setPage, setSortObject]
);

// selection logic
const {
selectedIds,
onSelect,
onToggleItem,
onUnselectItems,
} = useSelectionState();

// 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);
}
});

// We do all the data processing (filtering, sorting, paginating) client-side
useEffect(() => {
if (!loaded) return;
// 1. filter
let tempData = data.filter(record =>
Object.entries(filterValues).every(([filterName, filterValue]) =>
Array.isArray(get(record, filterName))
? get(record, filterName).includes(filterValue)
: // eslint-disable-next-line eqeqeq
filterValue == get(record, filterName)
)
);
// 2. sort
if (sort.field) {
tempData = tempData.sort((a, b) => {
if (get(a, sort.field) > get(b, sort.field)) {
return sort.order === 'ASC' ? 1 : -1;
}
if (get(a, sort.field) < get(b, sort.field)) {
return sort.order === 'ASC' ? -1 : 1;
}
return 0;
});
}
// 3. paginate
tempData = tempData.slice((page - 1) * perPage, page * perPage);
setFinalData(indexById(tempData));
setFinalIds(
tempData
.filter(data => typeof data !== 'undefined')
.map(data => data.id)
);
}, [
data,
filterValues,
const listProps = useList({
error,
filter,
initialData: data,
initialIds: ids,
initialPage,
initialPerPage,
initialSort,
loading,
loaded,
page,
perPage,
setFinalData,
setFinalIds,
sort.field,
sort.order,
]);

useEffect(() => {
if (loaded !== loadedState) {
setLoadedState(loaded);
}
}, [loaded, loadedState, setLoadedState]);

useEffect(() => {
if (loading !== loadingState) {
setLoadingState(loading);
}
}, [loading, loadingState, setLoadingState]);
});

return {
basePath: basePath
? basePath.replace(resource, reference)
: `/${reference}`,
currentSort: sort,
data: finalData,
...listProps,
defaultTitle: null,
error,
displayedFilters,
filterValues,
hasCreate: false,
hideFilter,
ids: finalIds,
loaded: loadedState,
loading: loadingState,
onSelect,
onToggleItem,
onUnselectItems,
page,
perPage,
refetch,
resource: reference,
selectedIds,
setFilters,
setPage,
setPerPage,
setSort,
showFilter,
total: finalIds.length,
};
};

Expand Down
1 change: 1 addition & 0 deletions packages/ra-core/src/controller/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,4 @@ export * from './button';
export * from './details';
export * from './RecordContext';
export * from './saveModifiers';
export * from './useList';
Loading