Repository: gregnb/mui-datatables
Pull request #948 (2019-09-20 23:21:17)

Fix issue where rows equal to row option would cause error
Closes https://github.com/gregnb/mui-datatables/issues/942 and https://github.com/gregnb/mui-datatables/issues/994.

coveralls: 
[![Coverage Status](https://coveralls.io/builds/25842851/badge)](https://coveralls.io/builds/25842851)

Coverage decreased (-0.04%) to 76.597% when pulling **d2c29c1f9fcb13a766c6da8884443ee143f486d9 on bugfix/issue-942-page-out-of-bounds** into **f0ea9e58d82839c57a4dfd4a342b6649932660a7 on master**.


Patch:
diff --git a/src/MUIDataTable.js b/src/MUIDataTable.js
index ecae4a8..12c4ad2 100644
--- a/src/MUIDataTable.js
+++ b/src/MUIDataTable.js
@@ -17,7 +17,7 @@ import TableResize from './components/TableResize';
 import TableToolbar from './components/TableToolbar';
 import TableToolbarSelect from './components/TableToolbarSelect';
 import textLabels from './textLabels';
-import { buildMap, getCollatorComparator, sortCompare } from './utils';
+import { buildMap, getCollatorComparator, sortCompare, getPageValue } from './utils';
 
 const defaultTableStyles = theme => ({
   root: {},
@@ -886,20 +886,16 @@ class MUIDataTable extends React.Component {
   };
 
   changeRowsPerPage = rows => {
-    /**
-     * After changing rows per page recalculate totalPages and checks its if current page not higher.
-     * Otherwise sets current page the value of nextTotalPages
-     */
     const rowCount = this.options.count || this.state.displayData.length;
-    const nextTotalPages = Math.floor(rowCount / rows);
 
     this.setState(
       () => ({
         rowsPerPage: rows,
-        page: this.state.page > nextTotalPages ? nextTotalPages : this.state.page,
+        page: getPageValue(rowCount, rows, this.state.page),
       }),
       () => {
         this.setTableAction('changeRowsPerPage');
+
         if (this.options.onChangeRowsPerPage) {
           this.options.onChangeRowsPerPage(this.state.rowsPerPage);
         }
diff --git a/src/components/TableBody.js b/src/components/TableBody.js
index a8ed200..a55558e 100644
--- a/src/components/TableBody.js
+++ b/src/components/TableBody.js
@@ -7,6 +7,7 @@ import TableBodyRow from './TableBodyRow';
 import TableSelectCell from './TableSelectCell';
 import { withStyles } from '@material-ui/core/styles';
 import cloneDeep from 'lodash.clonedeep';
+import { getPageValue } from '../utils';
 
 const defaultBodyStyles = {
   root: {},
@@ -55,12 +56,12 @@ class TableBody extends React.Component {
     if (this.props.options.serverSide) return data.length ? data : null;
 
     let rows = [];
-    const totalPages = Math.floor(count / rowsPerPage);
-    const fromIndex = page === 0 ? 0 : page * rowsPerPage;
-    const toIndex = Math.min(count, (page + 1) * rowsPerPage);
+    const highestPageInRange = getPageValue(count, rowsPerPage, page);
+    const fromIndex = highestPageInRange === 0 ? 0 : highestPageInRange * rowsPerPage;
+    const toIndex = Math.min(count, (highestPageInRange + 1) * rowsPerPage);
 
-    if (page > totalPages && totalPages !== 0) {
-      console.warn('Current page is out of range.');
+    if (page > highestPageInRange) {
+      console.warn('Current page is out of range, using the highest page that is in range instead.');
     }
 
     for (let rowIndex = fromIndex; rowIndex < count && rowIndex < toIndex; rowIndex++) {
diff --git a/src/components/TablePagination.js b/src/components/TablePagination.js
index cc20ea1..e091164 100644
--- a/src/components/TablePagination.js
+++ b/src/components/TablePagination.js
@@ -4,6 +4,7 @@ import MuiTableRow from '@material-ui/core/TableRow';
 import MuiTableFooter from '@material-ui/core/TableFooter';
 import MuiTablePagination from '@material-ui/core/TablePagination';
 import { withStyles } from '@material-ui/core/styles';
+import { getPageValue } from '../utils';
 
 const defaultPaginationStyles = {
   root: {
@@ -63,7 +64,7 @@ class TablePagination extends React.Component {
             }}
             count={count}
             rowsPerPage={rowsPerPage}
-            page={page}
+            page={getPageValue(count, rowsPerPage, page)}
             labelRowsPerPage={textLabels.rowsPerPage}
             labelDisplayedRows={({ from, to, count }) => `${from}-${to} ${textLabels.displayRows} ${count}`}
             backIconButtonProps={{
diff --git a/src/utils.js b/src/utils.js
index e376eb1..22dab1e 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -5,6 +5,12 @@ function buildMap(rows) {
   }, {});
 }
 
+function getPageValue(count, rowsPerPage, page) {
+  const totalPages = count === rowsPerPage ? 0 : Math.floor(count / rowsPerPage);
+
+  return page > totalPages ? totalPages : page;
+}
+
 function getCollatorComparator() {
   if (!!Intl) {
     const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
@@ -90,4 +96,4 @@ function createCSVDownload(columns, data, options) {
   }
 }
 
-export { buildMap, getCollatorComparator, sortCompare, createCSVDownload };
+export { buildMap, getPageValue, getCollatorComparator, sortCompare, createCSVDownload };


Test patch:
diff --git a/test/MUIDataTablePagination.test.js b/test/MUIDataTablePagination.test.js
index a5a6e9b..71719c1 100644
--- a/test/MUIDataTablePagination.test.js
+++ b/test/MUIDataTablePagination.test.js
@@ -46,4 +46,13 @@ describe('<TablePagination />', function() {
     instance.handlePageChange(null, 1);
     assert.strictEqual(changePage.callCount, 1);
   });
+
+  it('should correctly change page to be in bounds if out of bounds page was set', () => {
+    // Set a page that is too high for the count and rowsPerPage
+    const mountWrapper = mount(<TablePagination options={options} count={5} page={1} rowsPerPage={10} />);
+    const actualResult = mountWrapper.find(MuiTablePagination).props().page;
+
+    // material-ui v3 does some internal calculations to protect against out of bounds pages, but material v4 does not
+    assert.strictEqual(actualResult, 0);
+  });
 });