Files
2026-11-06 10:02:29 +00:00

109 lines
4.6 KiB
TypeScript

import { JSX } from "react";
import { getUsers, addUser, editUser, removeUser } from "../actions/UserAction";
import { hashPassword } from "../lib/auth";
export default async function UsersPage(): Promise<JSX.Element> {
const users = await getUsers(); // fetches all users from database, returns array of records
return (
<div>
<form
action={async (formData: FormData) => { // during build time, next generates this func on the server
"use server"; /// when submit is pressed it sends formdata and func reference to server and next executes it
const name = formData.get("name") as string;
const email = formData.get("email") as string;
const pass = formData.get("pass") as string;
const hashedPass = await hashPassword(pass);
if (email && pass) { // if all required fields present then add user
const result = await addUser({ name, email, pass:hashedPass });
}
}}
className="grid grid-cols-1 md:grid-cols-4 gap-3 items-end mt-2">
<input
type="text"
name="name"
placeholder="Name"
className="input input-bordered input-sm w-full"
/>
<input
type="email"
name="email"
placeholder="Email"
className="input input-bordered input-sm w-full"
required
/>
<input
type="password"
name="pass"
placeholder="Password"
className="input input-bordered input-sm w-full"
required
/>
<button type="submit" className="btn btn-primary btn-sm">
Add User
</button>
</form>
<table className="table table-zebra w-full">
<thead>
<tr>
<th> ID</th>
<th> Name</th>
<th> Email</th>
<th className="text-right"> Actions</th>
</tr>
</thead>
<tbody>
{users.map((user) => ( // maps each record in user array to a table row, performs func on every obj/record where user refers to current obj
<tr key={user.id}>
<td className="font-mono">{user.id}</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td className="text-right flex justify-end gap-2">
{/* <form
action={async () => {
"use server";
await editUser(user.id, {
name: `${user.name} (Edited)`,
});
}}
>
<button
type="submit"
className="btn btn-xs btn-outline btn-warning"
>
Edit
</button>
</form> */}
<form
action = {async () => {
"use server";
await removeUser(user.id);
}}
>
<button
type="submit"
className="btn btn-xs btn-outline btn-error"
>
Remove
</button>
</form>
</td>
</tr>
))}
{users.length === 0 && ( // if length of array is 0 (no users in db)
<tr>
<td colSpan={4} className="text-center py-4 text-base-content/60">
No users found in database.
</td>
</tr>
)}
</tbody>
</table>
</div>
);
}