Skip to content

Commit

Permalink
fix: page able to go out of bounds when resetPageOnRowChange is false
Browse files Browse the repository at this point in the history
  • Loading branch information
gregbaroni committed Oct 18, 2023
1 parent 6ff8b99 commit 49f7141
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/components/Table/UncontrolledTable.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,13 @@ export default class UncontrolledTable extends React.Component {
this.setState({ expanded: [] });
}

if (nextProps.resetPageOnRowChange && rowsChanged) {
this.setState({ page: 0 });
if (rowsChanged) {
const numPages = Math.ceil(nextProps.rows.length / nextProps.pageSize);
if (nextProps.resetPageOnRowChange || !numPages) {
this.setState({ page: 0 });
} else if ((this.state.page + 1) > numPages) {
this.setState({ page: numPages - 1 });
}
}

if (selectedChanged) {
Expand Down Expand Up @@ -213,6 +218,7 @@ export default class UncontrolledTable extends React.Component {
onExpand,
onSort,
onPageChange,
resetPageOnRowChange,
onVisibleRowsChange,
...props
} = this.props;
Expand Down
23 changes: 23 additions & 0 deletions src/components/Table/UncontrolledTable.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,7 @@ describe('<UncontrolledTable />', () => {
rows = [
{ name: 'Alpha', key: '1' },
{ name: 'Bravo', key: '2' },
{ name: 'Charlie', key: '3' },
];
expanded = [{ name: 'Alpha', key: '1' }];
selected = [{ name: 'Bravo', key: '2' }];
Expand Down Expand Up @@ -703,6 +704,7 @@ describe('<UncontrolledTable />', () => {
rows={rows}
expanded={expanded}
page={1}
pageSize={2}
selected={selected}
resetPageOnRowChange={false}
/>
Expand All @@ -729,6 +731,27 @@ describe('<UncontrolledTable />', () => {
assert.strictEqual(wrapper.state().page, 1, 'the page state should still be 1');
});

it('should set page to the last page if rows change and user is now out of page bounds when resetPageOnRowChange is false', () => {
wrapper = mount(
<UncontrolledTable
columns={columns}
rows={rows}
expanded={expanded}
page={2}
pageSize={1}
selected={selected}
resetPageOnRowChange={false}
/>
);
assert.strictEqual(wrapper.props().page, 2, 'the page prop should be 2');

const newProps = JSON.parse(JSON.stringify(wrapper.props()));
newProps.rows.pop();
wrapper.instance().UNSAFE_componentWillReceiveProps(newProps);

assert.strictEqual(wrapper.state().page, 1, 'the page state should now be 1');
});

it('should reset state for selected if a change is detected in the selected key attributes have changed', () => {
assert(wrapper.props().selected.length > 0, 'the selected props should be non empty');

Expand Down

0 comments on commit 49f7141

Please sign in to comment.