Skip to content

Commit

Permalink
Return pageSize as part of usePaginatedAPIFetch result
Browse files Browse the repository at this point in the history
  • Loading branch information
acelaya committed Nov 7, 2024
1 parent ebbcca9 commit b93a0c4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,8 @@ export default function DashboardActivityFilters({
assignmentFilters,
);

console.log(assignmentsResults);

const studentsFilters = useMemo(
() => ({
assignment_id: selectedAssignmentIds,
Expand Down
18 changes: 17 additions & 1 deletion lms/static/scripts/frontend_apps/utils/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,14 @@ export type PaginatedFetchResult<T> = Omit<FetchResult<T>, 'mutate'> & {
/** Determines if currently loading the first page */
isLoadingFirstPage: boolean;
loadNextPage: () => void;

/**
* Determines the size of every page (maximum number of results returned per
* page).
* If the API indicates there is no more pages, this will be undefined. You
* can trust `data.length` as the total number of items in that case.
*/
pageSize?: number;
};

/**
Expand All @@ -338,6 +346,7 @@ export function usePaginatedAPIFetch<
): PaginatedFetchResult<ListType> {
const [nextPageURL, setNextPageURL] = useState<string>();
const [currentList, setCurrentList] = useState<ListType>();
const [pageSize, setPageSize] = useState<number>();

const fetchResult = useAPIFetch<FetchType>(
nextPageURL ?? path,
Expand All @@ -350,15 +359,21 @@ export function usePaginatedAPIFetch<
}
}, [fetchResult.data?.pagination.next, fetchResult.isLoading]);

// Every time data is loaded, append the result to the list
useEffect(() => {
// Every time data is loaded, append the result to the list
setCurrentList(prev => {
if (!fetchResult.data) {
return prev;
}

return [...(prev ?? []), ...fetchResult.data[prop]] as ListType;
});

// Set pageSize if the API indicated there are more pages.
// Once page size has been set, we keep the value, ignoring next page loads
if (fetchResult.data?.pagination.next) {
setPageSize(prev => prev ?? fetchResult.data?.[prop].length);
}
}, [prop, fetchResult.data]);

// Every time params change, discard previous pages and start from scratch
Expand All @@ -382,5 +397,6 @@ export function usePaginatedAPIFetch<
error: fetchResult.error,
retry: fetchResult.retry,
loadNextPage,
pageSize,
};
}

0 comments on commit b93a0c4

Please sign in to comment.