Skip to content

Commit

Permalink
DataViews Pagination: improve pagination logic to handle empty pages
Browse files Browse the repository at this point in the history
  • Loading branch information
yogeshbhutkar committed Jan 16, 2025
1 parent 74986ed commit 460f181
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
3 changes: 2 additions & 1 deletion packages/dataviews/src/components/dataviews-footer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,12 @@ export default function DataViewsFooter() {
const hasBulkActions =
useSomeItemHasAPossibleBulkAction( actions, data ) &&
[ LAYOUT_TABLE, LAYOUT_GRID ].includes( view.type );
const currentPage = view.page ?? 1;

if (
! totalItems ||
! totalPages ||
( totalPages <= 1 && ! hasBulkActions )
( totalPages <= 1 && currentPage <= totalPages && ! hasBulkActions )
) {
return null;
}
Expand Down
21 changes: 19 additions & 2 deletions packages/dataviews/src/components/dataviews-pagination/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ import {
__experimentalHStack as HStack,
SelectControl,
} from '@wordpress/components';
import { createInterpolateElement, memo, useContext } from '@wordpress/element';
import {
createInterpolateElement,
memo,
useContext,
useEffect,
} from '@wordpress/element';
import { sprintf, __, _x, isRTL } from '@wordpress/i18n';
import { next, previous } from '@wordpress/icons';

Expand All @@ -20,13 +25,25 @@ function DataViewsPagination() {
view,
onChangeView,
paginationInfo: { totalItems = 0, totalPages },
data,
} = useContext( DataViewsContext );

const currentPage = view.page ?? 1;

// If the current page is not the first page, and there are no items on the current page, go to the previous page.
useEffect( () => {
if ( currentPage !== 1 && ! data.length ) {
onChangeView( {
...view,
page: currentPage - 1,
} );
}
}, [ data.length, currentPage, view, onChangeView ] );

if ( ! totalItems || ! totalPages ) {
return null;
}

const currentPage = view.page ?? 1;
const pageSelectOptions = Array.from( Array( totalPages ) ).map(
( _, i ) => {
const page = i + 1;
Expand Down

0 comments on commit 460f181

Please sign in to comment.