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

[DataGrid] Fix server-side pagination #639

Merged
merged 7 commits into from
Nov 27, 2020
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
12 changes: 1 addition & 11 deletions packages/grid/_modules_/grid/GridComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -202,17 +202,7 @@ export const GridComponent = React.forwardRef<HTMLDivElement, GridComponentProps
!!gridState.options.pagination &&
gridState.pagination.pageSize != null &&
!gridState.options.hideFooterPagination &&
(customComponents.paginationComponent || (
<Pagination
setPage={apiRef.current.setPage}
currentPage={gridState.pagination.page}
pageCount={gridState.pagination.pageCount}
pageSize={gridState.pagination.pageSize}
rowCount={gridState.pagination.rowCount}
setPageSize={apiRef.current.setPageSize}
rowsPerPageOptions={gridState.options.rowsPerPageOptions}
/>
))
(customComponents.paginationComponent || <Pagination />)
}
/>
)}
Expand Down
48 changes: 21 additions & 27 deletions packages/grid/_modules_/grid/components/pagination.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
import * as React from 'react';
import TablePagination from '@material-ui/core/TablePagination';
import { makeStyles, Theme } from '@material-ui/core/styles';

export interface PaginationComponentProps {
pageCount: number;
setPage: (pageCount: number) => void;
setPageSize: (pageSize: number) => void;
currentPage: number;
rowCount: number;
pageSize: number;
rowsPerPageOptions?: number[];
}
import { useGridSelector } from '../hooks/features/core/useGridSelector';
import { paginationSelector } from '../hooks/features/pagination/paginationSelector';
import { optionsSelector } from '../hooks/utils/useOptionsProp';
import { ApiContext } from './api-context';

// Used to hide the drop down select from the TablePaginagion
const useStyles = makeStyles((theme: Theme) => ({
Expand All @@ -31,42 +25,42 @@ const useStyles = makeStyles((theme: Theme) => ({
},
}));

export const Pagination: React.FC<PaginationComponentProps> = ({
setPage,
setPageSize,
pageSize,
rowCount,
currentPage,
rowsPerPageOptions,
}) => {
export function Pagination() {
const classes = useStyles();
const apiRef = React.useContext(ApiContext);
const paginationState = useGridSelector(apiRef, paginationSelector);
const options = useGridSelector(apiRef, optionsSelector);

const onPageSizeChange = React.useCallback(
(event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
const newPageSize = Number(event.target.value);
setPageSize(newPageSize);
apiRef!.current!.setPageSize(newPageSize);
},
[setPageSize],
[apiRef],
);

const onPageChange = React.useCallback(
(event: any, page: number) => {
setPage(page + 1);
apiRef!.current!.setPage(page + 1);
},
[setPage],
[apiRef],
);

return (
<TablePagination
classes={classes}
component="div"
count={rowCount}
page={currentPage - 1}
count={paginationState.rowCount}
page={paginationState.page - 1}
onChangePage={onPageChange}
rowsPerPageOptions={
rowsPerPageOptions && rowsPerPageOptions.indexOf(pageSize) > -1 ? rowsPerPageOptions : []
options.rowsPerPageOptions &&
options.rowsPerPageOptions.indexOf(paginationState.pageSize) > -1
? options.rowsPerPageOptions
: []
}
rowsPerPage={pageSize}
rowsPerPage={paginationState.pageSize}
onChangeRowsPerPage={onPageSizeChange}
/>
);
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ export const FilterInputValue: React.FC<TypeFilterInputValueProps> = ({
};
}, []);

React.useEffect(() => {
setFilterValueState(item.value || '');
}, [item.value]);

const inputProps = applying ? { endAdornment: <LoadIcon /> } : undefined;

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createSelector } from 'reselect';
import { FilterItem } from '../../../models/filterItem';
import { RowModel } from '../../../models/rows';
import { GridState } from '../core/gridState';
import { rowCountSelector } from '../rows/rowsSelector';
import { sortedRowsSelector } from '../sorting/sortingSelector';
import { FilterModelState } from './FilterModelState';
import { VisibleRowsState } from './visibleRowsState';
Expand All @@ -17,9 +18,18 @@ export const visibleSortedRowsSelector = createSelector<
return [...sortedRows].filter((row) => visibleRowsState.visibleRowsLookup[row.id] !== false);
});

export const visibleRowCountSelector = createSelector<GridState, RowModel[], number>(
export const visibleRowCountSelector = createSelector<
GridState,
RowModel[],
RowModel[],
number,
number
>(
visibleSortedRowsSelector,
(rows) => rows.length,
sortedRowsSelector,
rowCountSelector,
(visibleRows, sortedRows, totalRowsCount) =>
totalRowsCount - (sortedRows.length - visibleRows.length),
);

export const filterStateSelector: (state: GridState) => FilterModelState = (state) => state.filter;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,24 @@ export const setPageSizeStateUpdate = (
return state;
}

const newState: PaginationState = { ...state, pageSize };
const newState: PaginationState = {
...state,
pageSize,
pageCount: getPageCount(pageSize, state.rowCount),
};
return newState;
};

export const setRowCountStateUpdate = (state, payload): PaginationState => {
const { totalRowCount } = payload;
if (state.rowCount !== totalRowCount) {
const newPageCount = getPageCount(state.pageSize, totalRowCount);
return { ...state, pageCount: newPageCount, rowCount: totalRowCount };
return {
...state,
pageCount: newPageCount,
rowCount: totalRowCount,
page: state.page > newPageCount ? newPageCount : state.page,
};
}
return state;
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import * as React from 'react';
import { PAGE_CHANGED, PAGESIZE_CHANGED, RESIZE } from '../../../constants/eventsConstants';
import { containerSizesSelector } from '../../../components/viewport';
import { PAGE_CHANGED, PAGESIZE_CHANGED } from '../../../constants/eventsConstants';
import { ApiRef } from '../../../models/api/apiRef';
import { PaginationApi } from '../../../models/api/paginationApi';
import { PaginationProps } from '../../../models/paginationProps';
import { PageChangeParams } from '../../../models/params/pageChangeParams';
import { useApiEventHandler } from '../../root/useApiEventHandler';
import { useApiMethod } from '../../root/useApiMethod';
import { useLogger } from '../../utils/useLogger';
import { optionsSelector } from '../../utils/useOptionsProp';
import { visibleColumnsLengthSelector } from '../columns/columnsSelector';
import { useGridReducer } from '../core/useGridReducer';
import { useGridSelector } from '../core/useGridSelector';
import { rowCountSelector } from '../rows/rowsSelector';
import { visibleRowCountSelector } from '../filter/filterSelector';
import {
INITIAL_PAGINATION_STATE,
PaginationActions,
Expand All @@ -25,7 +24,7 @@ import {

const PAGINATION_STATE_ID = 'pagination';

export const usePagination = (apiRef: ApiRef): PaginationProps => {
export const usePagination = (apiRef: ApiRef): void => {
const logger = useLogger('usePagination');

const { gridState, dispatch } = useGridReducer<PaginationState, PaginationActions>(
Expand All @@ -35,8 +34,8 @@ export const usePagination = (apiRef: ApiRef): PaginationProps => {
{ ...INITIAL_PAGINATION_STATE },
);
const options = useGridSelector(apiRef, optionsSelector);
const totalRowCount = useGridSelector(apiRef, rowCountSelector);
const visibleColumnsLength = useGridSelector(apiRef, visibleColumnsLengthSelector);
const visibleRowCount = useGridSelector(apiRef, visibleRowCountSelector);
const containerSizes = useGridSelector(apiRef, containerSizesSelector);

const setPage = React.useCallback(
(page: number) => {
Expand Down Expand Up @@ -76,25 +75,9 @@ export const usePagination = (apiRef: ApiRef): PaginationProps => {
[apiRef],
);

const resetAutopageSize = React.useCallback(() => {
if (options.autoPageSize) {
const containerProps = apiRef?.current?.getContainerPropsState();
const autoPagesize = containerProps?.viewportPageSize;
if (autoPagesize) {
logger.debug(`Setting autoPagesize to ${autoPagesize}`);
setPageSize(autoPagesize);
}
}
}, [options.autoPageSize, apiRef, logger, setPageSize]);

useApiEventHandler(apiRef, RESIZE, resetAutopageSize);
useApiEventHandler(apiRef, PAGE_CHANGED, options.onPageChange);
useApiEventHandler(apiRef, PAGESIZE_CHANGED, options.onPageSizeChange);

React.useEffect(() => {
dispatch(setRowCountActionCreator({ totalRowCount }));
}, [apiRef, dispatch, totalRowCount]);

React.useEffect(() => {
dispatch(setPaginationModeActionCreator({ paginationMode: options.paginationMode! }));
}, [apiRef, dispatch, options.paginationMode]);
Expand All @@ -110,10 +93,14 @@ export const usePagination = (apiRef: ApiRef): PaginationProps => {
}, [options.autoPageSize, options.pageSize, logger, setPageSize]);

React.useEffect(() => {
if (options.autoPageSize && visibleColumnsLength > 0) {
resetAutopageSize();
if (options.autoPageSize && containerSizes && containerSizes?.viewportPageSize > 0) {
setPageSize(containerSizes?.viewportPageSize);
}
}, [options.autoPageSize, resetAutopageSize, visibleColumnsLength]);
}, [containerSizes, options.autoPageSize, setPageSize]);

React.useEffect(() => {
dispatch(setRowCountActionCreator({ totalRowCount: visibleRowCount }));
}, [apiRef, dispatch, visibleRowCount]);

React.useEffect(() => {
if (apiRef.current?.isInitialised) {
Expand All @@ -129,10 +116,4 @@ export const usePagination = (apiRef: ApiRef): PaginationProps => {
};

useApiMethod(apiRef, paginationApi, 'paginationApi');

return {
...gridState.pagination,
setPage,
setPageSize,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,11 @@ export const useVirtualRows = (
return null;
}
let minRowIdx = 0;
if (options.pagination && paginationState.pageSize != null) {
if (
options.pagination &&
paginationState.pageSize != null &&
paginationState.paginationMode === 'client'
) {
minRowIdx =
paginationState.pageSize * (paginationState.page - 1 > 0 ? paginationState.page - 1 : 0);
}
Expand All @@ -77,7 +81,13 @@ export const useVirtualRows = (
const rowProps: RenderRowProps = { page, firstRowIdx, lastRowIdx };
return rowProps;
},
[apiRef, options.pagination, paginationState.pageSize, paginationState.page],
[
apiRef,
options.pagination,
paginationState.pageSize,
paginationState.paginationMode,
paginationState.page,
],
);

const getRenderingState = React.useCallback((): Partial<RenderContextProps> | null => {
Expand Down
55 changes: 54 additions & 1 deletion packages/grid/data-grid/src/DataGrid.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import PropTypes from 'prop-types';
import { createClientRender, fireEvent, screen, ErrorBoundary } from 'test/utils';
import { useFakeTimers } from 'sinon';
import { expect } from 'chai';
import { DataGrid } from '@material-ui/data-grid';
import { DataGrid, RowsProp } from '@material-ui/data-grid';
import { getColumnValues } from 'test/utils/helperFn';

describe('<DataGrid />', () => {
Expand Down Expand Up @@ -93,6 +93,59 @@ describe('<DataGrid />', () => {
done();
}, 50);
});

it('should support server side pagination', () => {
const ServerPaginationGrid = () => {
const [page, setPage] = React.useState(1);
const [rows, setRows] = React.useState<RowsProp>([]);

const handlePageChange = (params) => {
setPage(params.page);
};

React.useEffect(() => {
let active = true;

(async () => {
const newRows = [
{
id: page,
brand: `Nike ${page}`,
},
];

if (!active) {
return;
}

setRows(newRows);
})();

return () => {
active = false;
};
}, [page]);

return (
<div style={{ height: 300, width: 300 }}>
<DataGrid
{...defaultProps}
rows={rows}
pagination
pageSize={1}
rowCount={3}
paginationMode="server"
onPageChange={handlePageChange}
/>
</div>
);
};

render(<ServerPaginationGrid />);
expect(getColumnValues()).to.deep.equal(['Nike 1']);
fireEvent.click(screen.getByRole('button', { name: /next page/i }));
expect(getColumnValues()).to.deep.equal(['Nike 2']);
});
});

describe('warnings', () => {
Expand Down
Loading