Skip to content

Commit

Permalink
Persist pages on url and hydrate on page load (#2826)
Browse files Browse the repository at this point in the history
  • Loading branch information
anderson-oki authored Jan 16, 2025
1 parent d572ab7 commit dbcbf4e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
17 changes: 15 additions & 2 deletions frontend/src/apis/queries/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useState } from "react";
import { useSearchParams } from "react-router";
import {
QueryKey,
useQuery,
Expand Down Expand Up @@ -34,7 +35,12 @@ export function usePaginationQuery<
): UsePaginationQueryResult<TObject> {
const client = useQueryClient();

const [page, setIndex] = useState(0);
const [searchParams] = useSearchParams();

const [page, setIndex] = useState(
searchParams.get("page") ? Number(searchParams.get("page")) - 1 : 0,
);

const pageSize = usePageSize();

const start = page * pageSize;
Expand Down Expand Up @@ -62,7 +68,14 @@ export function usePaginationQuery<
}
});
}
}, [results.isSuccess, results.data, client, cacheIndividual, queryKey]);
}, [
results.isSuccess,
results.data,
client,
cacheIndividual,
queryKey,
page,
]);

const totalCount = data?.total ?? 0;
const pageCount = Math.ceil(totalCount / pageSize);
Expand Down
17 changes: 10 additions & 7 deletions frontend/src/components/tables/PageControl.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { FunctionComponent, useEffect } from "react";
import { FunctionComponent } from "react";
import { useSearchParams } from "react-router";
import { Group, Pagination, Text } from "@mantine/core";
import { useIsLoading } from "@/contexts";

Expand All @@ -22,11 +23,7 @@ const PageControl: FunctionComponent<Props> = ({
const end = Math.min(size * (index + 1), total);

const isLoading = useIsLoading();

// Jump to first page if total page count changes
useEffect(() => {
goto(0);
}, [total, goto]);
const [searchParams, setSearchParams] = useSearchParams();

return (
<Group p={16} justify="space-between">
Expand All @@ -37,7 +34,13 @@ const PageControl: FunctionComponent<Props> = ({
size="sm"
color={isLoading ? "gray" : "primary"}
value={index + 1}
onChange={(page) => goto(page - 1)}
onChange={(page) => {
searchParams.set("page", page.toString());

setSearchParams(searchParams, { replace: true });

return goto(page - 1);
}}
hidden={count <= 1}
total={count}
></Pagination>
Expand Down

0 comments on commit dbcbf4e

Please sign in to comment.