import { apiCall } from "@/lib"; import { User } from "@/Zustand"; import { Button, Checkbox, Table, TableBody, TableCell, TableColumn, TableHeader, TableRow, Tooltip, } from "@nextui-org/react"; import { useAsyncList } from "@react-stately/data"; import { FormEvent, useState } from "react"; import AddUser from "./AddUser"; import { Edit } from "@carbon/icons-react"; import EditUser from "./EditUser"; export default function Users() { const [showAddUser, setShowAddUser] = useState(false); const [editUser, setEditUser] = useState(); const users = useAsyncList({ async load() { const result = await apiCall("GET", "users"); if (result.ok) { const users = (await result.json()) as User[]; return { items: users, }; } else { return { items: [], }; } }, async sort({ items, sortDescriptor }) { return { items: items.sort((a, b) => { let cmp = 0; switch (sortDescriptor.column) { case "admin": if (a.admin && !b.admin) { cmp = -1; } else if (!a.admin && b.admin) { cmp = 1; } break; case "userName": cmp = a.userName.localeCompare(b.userName); } if (sortDescriptor.direction === "descending") { cmp *= -1; } return cmp; }), }; }, }); // send an addUser request to the backend then reload the table async function addUser(e: FormEvent) { const data = Object.fromEntries(new FormData(e.currentTarget)); const result = await apiCall("POST", "users", undefined, { ...data, admin: data.admin === "admin", }); if (result.ok) { users.reload(); } } // content above the user-tabel const topContent = ( <> ); return (
Username Admin Edit {(user) => ( {user.userName} )}
void addUser(e)} /> !isOpen ? setEditUser(undefined) : undefined } onSuccess={() => { users.reload(); setEditUser(undefined); }} />
); }