Merge pull request #732 from LAION-AI/673-admin-page-pagination

Supporting user pagination on the web admin view
This commit is contained in:
Keith Stevens
2023-01-16 08:39:15 +09:00
committed by GitHub
5 changed files with 96 additions and 16 deletions
+58 -5
View File
@@ -11,6 +11,7 @@ import {
Th,
Thead,
Tr,
useToast,
} from "@chakra-ui/react";
import Link from "next/link";
import { useState } from "react";
@@ -18,26 +19,78 @@ import { get } from "src/lib/api";
import type { User } from "src/types/Users";
import useSWR from "swr";
interface Pagination {
/**
* The user's `display_name` used for pagination.
*/
cursor: string;
/**
* The pagination direction.
*/
direction: "forward" | "back";
}
/**
* Fetches users from the users api route and then presents them in a simple Chakra table.
*/
const UsersCell = () => {
const [pageIndex, setPageIndex] = useState(0);
const toast = useToast();
const [pagination, setPagination] = useState<Pagination>({ cursor: "", direction: "forward" });
const [users, setUsers] = useState<User[]>([]);
// Fetch and save the users.
// This follows useSWR's recommendation for simple pagination:
// https://swr.vercel.app/docs/pagination#when-to-use-useswr
useSWR(`/api/admin/users?pageIndex=${pageIndex}`, get, {
onSuccess: setUsers,
useSWR(`/api/admin/users?direction=${pagination.direction}&cursor=${pagination.cursor}`, get, {
onSuccess: (data) => {
// When no more users can be found, trigger a toast to indicate why no
// changes have taken place. We have to maintain a non-empty set of
// users otherwise we can't paginate using a cursor (since we've lost the
// cursor).
if (data.length === 0) {
toast({
title: "No more users",
status: "warning",
duration: 1000,
isClosable: true,
});
return;
}
setUsers(data);
},
});
const toPreviousPage = () => {
setPageIndex(Math.max(0, pageIndex - 1));
if (users.length >= 0) {
setPagination({
cursor: users[0].display_name,
direction: "back",
});
} else {
toast({
title: "Can not paginate when no users are found",
status: "warning",
duration: 1000,
isClosable: true,
});
}
};
const toNextPage = () => {
setPageIndex(pageIndex + 1);
if (users.length >= 0) {
setPagination({
cursor: users[users.length - 1].display_name,
direction: "forward",
});
} else {
toast({
title: "Can not paginate when no users are found",
status: "warning",
duration: 1000,
isClosable: true,
});
}
};
// Present users in a naive table.