Skip to content

Commit

Permalink
Fix getEntityRecordsTotalPages when per_page is not provided and …
Browse files Browse the repository at this point in the history
…relies on the defaults from REST API (#59983)

Co-authored-by: ntsekouras <[email protected]>
Co-authored-by: Mamaduka <[email protected]>
  • Loading branch information
3 people authored Mar 19, 2024
1 parent 19cd137 commit dbfed70
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
6 changes: 6 additions & 0 deletions packages/core-data/src/queried-data/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,9 @@ export function getQueriedTotalItems( state, query = {} ) {

return state.queries?.[ context ]?.[ stableKey ]?.meta?.totalItems ?? null;
}

export function getQueriedTotalPages( state, query = {} ) {
const { stableKey, context } = getQueryParts( query );

return state.queries?.[ context ]?.[ stableKey ]?.meta?.totalPages ?? null;
}
3 changes: 3 additions & 0 deletions packages/core-data/src/resolvers.js
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,9 @@ export const getEntityRecords =
totalItems: parseInt(
response.headers.get( 'X-WP-Total' )
),
totalPages: parseInt(
response.headers.get( 'X-WP-TotalPages' )
),
};
} else {
records = Object.values( await apiFetch( { path } ) );
Expand Down
11 changes: 10 additions & 1 deletion packages/core-data/src/selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@ import deprecated from '@wordpress/deprecated';
* Internal dependencies
*/
import { STORE_NAME } from './name';
import { getQueriedItems, getQueriedTotalItems } from './queried-data';
import {
getQueriedItems,
getQueriedTotalItems,
getQueriedTotalPages,
} from './queried-data';
import { DEFAULT_ENTITY_KEY } from './entities';
import {
getNormalizedCommaSeparable,
Expand Down Expand Up @@ -623,6 +627,11 @@ export const getEntityRecordsTotalPages = (
if ( query.per_page === -1 ) return 1;
const totalItems = getQueriedTotalItems( queriedState, query );
if ( ! totalItems ) return totalItems;
// If `per_page` is not set and the query relies on the defaults of the
// REST endpoint, get the info from query's meta.
if ( ! query.per_page ) {
return getQueriedTotalPages( queriedState, query );
}
return Math.ceil( totalItems / query.per_page );
};

Expand Down

0 comments on commit dbfed70

Please sign in to comment.