File size: 1,493 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
import { uniqueBy } from '@automattic/js-utils';
import { useInfiniteQuery } from '@tanstack/react-query';
import wpcom from 'calypso/lib/wp';
export const defaults = {
number: 100,
order: 'ASC',
order_by: 'display_name',
};
const extractPages = ( pages = [] ) => pages.flatMap( ( page ) => page.users );
const compareUnique = ( a, b ) => a.ID === b.ID;
const useUsersQuery = ( siteId, fetchOptions = {}, queryOptions = {} ) => {
const { search } = fetchOptions;
return useInfiniteQuery( {
queryKey: [ 'users', siteId, search ],
queryFn: ( { pageParam } ) =>
wpcom.req.get( `/sites/${ siteId }/users`, {
...defaults,
...fetchOptions,
offset: pageParam,
} ),
enabled: !! siteId,
initialPageParam: 0,
getNextPageParam: ( lastPage, allPages ) => {
const n = fetchOptions.number ?? defaults.number;
if ( lastPage.found <= allPages.length * n ) {
return;
}
return allPages.length * n;
},
select: ( data ) => {
/* @TODO:
* `uniqueBy` is necessary, because the API can return duplicates.
* This is most commonly seen where a user has both a "regular" user role
* such as Administrator and Editor, and has also been added as a "Viewer" .
*/
const users = uniqueBy( extractPages( data.pages ), compareUnique );
return {
users: uniqueBy( extractPages( data.pages ), compareUnique ),
total: users?.length ?? data.pages[ 0 ].found,
...data,
};
},
...queryOptions,
} );
};
export default useUsersQuery;
|