first commit

This commit is contained in:
Jeannette Chin committed 2026-10-04 14:28:26 +01:00
commit 5d6023a8af
52 files changed
+5830

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
const AuthLayout = ({ children }: { children: React.ReactNode }) => {
return (
<div className="min-h-[calc(100vh-8rem)] flex items-center justify-center p-4">
<div className="card w-full max-w-md bg-base-200 shadow-xl">
<div className="card-body">{children}</div>
</div>
</div>
);
};
export default AuthLayout;
+48
View File
@@ -0,0 +1,48 @@
"use client";
import Link from "next/link";
const CustomLoginForm = () => {
return (
<>
<form className="mt-4">
{" "}
<div className="form-control">
<label className="label">
<span className="label-text">Email</span>
</label>
<input
type="email"
placeholder="you@example.com"
className="input input-bordered w-full"
required
/>
</div>
<div className="form-control mt-4">
<label className="label">
<span className="label-text">Password</span>
</label>
<input
type="password"
placeholder="••••••••"
className="input input-bordered w-full"
required
/>
</div>
<div className="form-control mt-6">
<button type="submit" className="btn btn-primary w-full">
Sign In
</button>
</div>
</form>
<div className="divider">OR</div>
<p className="text-center">
Don&apos;t have an account?{" "}
<Link href="/register" className="link link-primary">
Sign up
</Link>
</p>
</>
);
};
export default CustomLoginForm;
+26
View File
@@ -0,0 +1,26 @@
const SigninButton = ({
text,
style,
callback,
formAction
}: {
text: string;
style: string;
callback?: () => void;
formAction?: any;
}) => {
return (
<div className="form-control mt-6">
<button
type="submit"
formAction={formAction}
className={style}
onClick={callback}
>
{text}
</button>
</div>
);
};
export default SigninButton;
+38
View File
@@ -0,0 +1,38 @@
"use client";
import CustomLoginForm from "./CustomLoginForm";
import SigninButton from "./SigninButton";
import { useState } from "react";
import { handleGoogleLogin } from "@/app/actions/GoogleAction";
const LoginPage = () => {
const [elogin, setElogin] = useState(false);
const ShowEmailLogin = () => {
setElogin(!elogin);
};
return (
<>
<h2 className="card-title text-2xl justify-center w-full">
Please Sign In
</h2>
<form className="mt-4">
<SigninButton
text="Google"
style="btn btn-primary w-full"
formAction={handleGoogleLogin}
/>
</form>
<div className="mt-4">
<SigninButton
text="Email"
style="btn btn-primary w-full"
callback={ShowEmailLogin}
/>
</div>
<div className="mt-4">{elogin ? <CustomLoginForm /> : ""}</div>
</>
);
};
export default LoginPage;
+75
View File
@@ -0,0 +1,75 @@
"use client";
import Link from "next/link";
const RegisterPage = () => {
return (
<>
<h2 className="card-title text-2xl justify-center">Create Account</h2>
<form className="mt-4">
<div className="form-control">
<label className="label">
<span className="label-text">Name</span>
</label>
<input
type="text"
placeholder="Your name"
className="input input-bordered w-full"
required
/>
</div>
<div className="form-control mt-4">
<label className="label">
<span className="label-text">Email</span>
</label>
<input
type="email"
placeholder="you@example.com"
className="input input-bordered w-full"
required
/>
</div>
<div className="form-control mt-4">
<label className="label">
<span className="label-text">Password</span>
</label>
<input
type="password"
placeholder="••••••••"
className="input input-bordered w-full"
required
minLength={6}
/>
</div>
<div className="form-control mt-4">
<label className="label">
<span className="label-text">Confirm Password</span>
</label>
<input
type="password"
placeholder="••••••••"
className="input input-bordered w-full"
required
/>
</div>
<div className="form-control mt-6">
<button type="submit" className="btn btn-primary w-full">
Create Account
</button>
</div>
</form>
<div className="divider">OR</div>
<p className="text-center">
Already have an account?{" "}
<Link href="/login" className="link link-primary">
Sign in
</Link>
</p>
</>
);
};
export default RegisterPage;
+18
View File
@@ -0,0 +1,18 @@
"use client";
import { useRef } from "react";
import { Provider } from "react-redux";
import { makeStore, AppStore } from "../lib/store";
export default function PeopleProvider({
children,
}: {
children: React.ReactNode;
}) {
const storeRef = useRef<AppStore>(undefined);
if (!storeRef.current) {
// Create the store instance the first time this renders
storeRef.current = makeStore();
}
return <Provider store={storeRef.current}>{children}</Provider>;
}
+17
View File
@@ -0,0 +1,17 @@
"use server";
import { auth, signIn, signOut } from "@/auth";
export async function handleGoogleLogin() {
console.log(`google action`);
await signIn("google", { redirectTo: "/" });
}
export async function checkGoogleSession() {
const session = await auth();
return session;
}
export async function handleGoogleSignout() {
await signOut({ redirectTo: "/login" });
}
+76
View File
@@ -0,0 +1,76 @@
"use server";
import { prisma } from "../lib/prisma";
import { revalidatePath } from "next/cache";
// --- 1. ADD USER ---
export async function addUser(data: {
name: string;
email: string;
pass: string;
}) {
try {
const newUser = await prisma.user.create({
data: {
name: data.name,
email: data.email,
password: data.pass,
},
});
// Refresh the page cache to display the new user immediately
revalidatePath("/users");
return { success: true, user: newUser };
} catch (error) {
console.error("Failed to add user:", error);
return {
success: false,
error: "Failed to create user. Email may already exist.",
};
}
}
// --- 2. EDIT USER ---
export async function editUser(
id: number,
data: { name?: string; email?: string; pass?: string },
) {
try {
const updatedUser = await prisma.user.update({
where: { id },
data: {
...(data.name && { name: data.name }),
...(data.email && { email: data.email }),
...(data.pass && { password: data.pass }),
},
});
revalidatePath("/users");
return { success: true, user: updatedUser };
} catch (error) {
console.error("Failed to update user:", error);
return { success: false, error: "Failed to update user." };
}
}
// --- 3. REMOVE USER ---
export async function removeUser(id: number) {
try {
const deletedUser = await prisma.user.delete({
where: { id },
});
revalidatePath("/users");
return { success: true, user: deletedUser };
} catch (error) {
console.error("Failed to remove user:", error);
return { success: false, error: "Failed to remove user." };
}
}
// --- 4. GET ALL USERS (Helper to render the list) ---
export async function getUsers() {
return await prisma.user.findMany({
orderBy: { id: "desc" },
});
}
+75
View File
@@ -0,0 +1,75 @@
"use server";
import { prisma } from "../lib/prisma";
import { revalidatePath } from "next/cache";
import { z } from "zod";
// Define the state shape returned to the client
export type FormState = {
success: boolean;
message?: string;
errors?: {
name?: string[];
email?: string[];
pass?: string[];
};
};
// Zod Validation Schema
const UserSchema = z.object({
name: z
.string({ error: "Name must be a string" })
.min(2, { error: "Name must be at least 2 characters" }),
email: z.email({ error: "Please enter a valid email address" }), // Direct top-level function
pass: z.string().min(6, { error: "Password must be at least 6 characters" }),
});
// --- ADD USER SERVER ACTION ---
export async function addUserAction(
prevState: FormState,
formData: FormData,
): Promise<FormState> {
// 1. Validate Form Input with Zod
const validatedFields = UserSchema.safeParse({
name: formData.get("name"),
email: formData.get("email"),
pass: formData.get("pass"),
});
// If validation fails, return targeted field errors
if (!validatedFields.success) {
// Map error issues directly to field names
const fieldErrors: Record<string, string[]> = {};
for (const issue of validatedFields.error.issues) {
const field = issue.path[0] as string;
if (field) {
fieldErrors[field] = fieldErrors[field] || [];
fieldErrors[field].push(issue.message);
}
}
return {
success: false,
message: "Validation failed. Please check your inputs.",
errors: fieldErrors,
};
}
const { name, email, pass } = validatedFields.data;
// 2. Perform Database Mutation
try {
await prisma.user.create({
data: { name, email, password: pass },
});
revalidatePath("/users");
return { success: true, message: "User added successfully!" };
} catch (error) {
console.error("Failed to create user:", error);
return {
success: false,
message: "Failed to create user. Email may already be registered.",
};
}
}
+2
View File
@@ -0,0 +1,2 @@
import { handlers } from "@/auth"; // Referring to the auth.ts we just created
export const { GET, POST } = handlers;
+26
View File
@@ -0,0 +1,26 @@
import { NextRequest, NextResponse } from "next/server";
export async function POST(request: NextRequest) {
const { email, password } = await request.json();
// const user = await prisma.user.findUnique({ where: { email } });
// if (user || !(await verifyPassword(password, user.password))) {
// return NextResponse.json({ error: "Invalid Credentials" }, { status: 401 });
// }
if (email !== "admin@test.com" || password !== "admin") {
return NextResponse.json({ error: "Invalid Credentials" }, { status: 401 });
}
//const token = generateToken(user);
const response = NextResponse.json({
message: "Login Successful",
user: { id: "1", name: "admin" }
});
// Set httponly cookie (can't be accessed by JavaScript)
//setAuthCookie(response, token);
return response;
}
+117
View File
@@ -0,0 +1,117 @@
"use client";
import { Links } from "./navbarData";
import Link from "next/link";
import { usePathname } from "next/navigation"; // for checking active links
import { useAuth } from "../hooks/useAuth";
const NavBar = () => {
const pathname = usePathname();
const { isAuthenticated, user, logout, isLoading } = useAuth();
console.log(`isAuthenticated ... ${isAuthenticated}`);
return (
<nav className="navbar bg-base-100 shadow-sm">
<div className="navbar-start">
<div className="dropdown">
<div tabIndex={0} role="button" className="btn btn-ghost lg:hidden">
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-5 w-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
{" "}
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M4 6h16M4 12h8m-8 6h16"
/>{" "}
</svg>
</div>
<ul
tabIndex={-1}
className="menu menu-sm dropdown-content bg-base-100 rounded-box z-1 mt-3 w-52 p-2 shadow"
>
{Links.map((l) => {
const { id, url, text } = l;
return (
<li
className={`${pathname === url ? "menu-active" : ""}`}
key={id}
>
{/* here we use Link */}
<Link href={url}>{text}</Link>
</li>
);
})}
</ul>
</div>
<a className="btn btn-ghost text-xl">Adv WebDev</a>
</div>
<div className="navbar-center hidden lg:flex">
<ul className="menu menu-horizontal px-1">
{Links.map((l) => {
const { id, url, text } = l;
return (
<li
className={`${pathname === url ? "menu-active" : ""}`}
key={id}
>
{/* here we use Link */}
<Link href={url}>{text}</Link>
</li>
);
})}
</ul>
</div>
<div className="navbar-end">
{isAuthenticated ? (
<div className="dropdown dropdown-end">
<div
tabIndex={0}
role="button"
className="btn btn-ghost btn-circle avatar placeholder"
>
<div className="bg-primary text-primary-content w-10 rounded-full flex items-center justify-center">
<span className="text-lg">
{user?.name?.charAt(0).toUpperCase()}
</span>
</div>
</div>
<ul
tabIndex={0}
className="menu menu-sm dropdown-content bg-base-100 rounded-box z-[1] mt-3 w-52 p-2 shadow"
>
<li className="menu-title">{user?.name}</li>
<li>
<button onClick={logout}>Logout</button>
</li>
</ul>
</div>
) : (
<div className="flex gap-2">
<Link href="/login" className="btn btn-ghost btn-sm">
Login
</Link>
<Link href="/register" className="btn btn-primary btn-sm">
Sign Up
</Link>
</div>
)}
{/* {" "}
<div className="flex gap-2">
<Link href="/login" className="btn btn-ghost btn-sm">
Login
</Link>
<Link href="/register" className="btn btn-primary btn-sm">
Sign Up
</Link>
</div> */}
</div>
</nav>
);
};
export default NavBar;
+7
View File
@@ -0,0 +1,7 @@
"use client";
import { AuthProvider } from "../hooks/useAuth";
export function Providers({ children }: { children: React.ReactNode }) {
return <AuthProvider>{children}</AuthProvider>;
}
+23
View File
@@ -0,0 +1,23 @@
interface Link {
id: number;
url: string;
text: string;
}
export const Links: Link[] = [
{
id: 1,
url: "/",
text: "home",
},
{
id: 2,
url: "/people",
text: "People",
},
{
id: 3,
url: "/newsletters",
text: "Newsletters",
},
];
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+33
View File
@@ -0,0 +1,33 @@
"use client";
export default function GlobalError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
return (
<html>
<body>
<div className="min-h-[50vh] flex items-center justify-center p-4">
<div className="text-center">
<div className="text-6xl mb-4">😵</div>
<h2 className="text-2xl font-bold mb-2">Something went wrong!</h2>
<p className="text-base-content/70 mb-4">
{error.message || "An unexpected error occurred"}
</p>
<div className="flex gap-4 justify-center">
<button onClick={() => reset()} className="btn btn-primary">
Try again
</button>
<a href="/" className="btn btn-ghost">
Go home
</a>
</div>
</div>
</div>
</body>
</html>
);
}
+55
View File
@@ -0,0 +1,55 @@
@import "tailwindcss";
@plugin "daisyui";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}
/* HTML: <div class="loader"></div> */
/* From Uiverse.io by satyamchaudharydev */
.loader {
margin-left: 50%;
margin-top: 15%;
width: 60px;
height: 60px;
}
.loader::before {
content: "";
box-sizing: border-box;
position: absolute;
width: 60px;
height: 60px;
border-radius: 50%;
border-top: 2px solid #8900ff;
border-right: 2px solid transparent;
animation: spinner8217 0.8s linear infinite;
}
@keyframes spinner8217 {
to {
transform: rotate(360deg);
}
}
+103
View File
@@ -0,0 +1,103 @@
"use client";
import {
createContext,
useContext,
useState,
useEffect,
useCallback,
ReactNode
} from "react";
import { useRouter } from "next/navigation";
import {
checkGoogleSession,
handleGoogleSignout
} from "../actions/GoogleAction";
interface User {
id: string | null | undefined;
email: string | null | undefined;
name: string | null | undefined;
}
interface AuthState {
user: User;
isAuthenticated: boolean;
isLoading: boolean;
}
interface AuthContextType extends AuthState {
checkGoogle: () => void;
logout: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: ReactNode }) {
const router = useRouter();
const user = {
id: "",
email: "",
name: ""
};
const [authState, setAuthState] = useState<AuthState>({
user: user,
isAuthenticated: false,
isLoading: true
});
const checkGoogle = async () => {
const session = await checkGoogleSession();
if (session) {
const currentUser: User = {
id: session.user?.id,
name: session.user?.name,
email: session.user?.email
};
setAuthState({
user: currentUser,
isAuthenticated: true,
isLoading: false
});
}
};
// Check auth status on mount
useEffect(() => {
checkGoogle();
}, []);
const logout = useCallback(async () => {
setAuthState({
user: user,
isAuthenticated: false,
isLoading: false
});
await handleGoogleSignout();
}, []);
const value: AuthContextType = {
...authState,
checkGoogle,
logout
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
/**
* useAuth hook - uses shared AuthContext
* All components using this hook share the same auth state
*/
export function useAuth() {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
}
+45
View File
@@ -0,0 +1,45 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import NavBar from "./components/NavBar";
import { Toaster } from "react-hot-toast";
import PeopleProvider from "./PeopleProvider";
import { Providers } from "./components/Providers";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"]
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"]
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app"
};
export default function RootLayout({
children
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html
lang="en"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
>
<body className="min-h-full flex flex-col">
<Providers>
<PeopleProvider>
<Toaster position="bottom-right" />
<NavBar />
{children}
</PeopleProvider>
</Providers>
</body>
</html>
);
}
+19
View File
@@ -0,0 +1,19 @@
import { PrismaClient } from "@/lib/generated/prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";
import { Pool } from "pg";
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
function createPrismaClient() {
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const adapter = new PrismaPg(pool);
return new PrismaClient({ adapter });
}
export const prisma = globalForPrisma.prisma ?? createPrismaClient();
if (process.env.NODE_ENV !== "production") {
globalForPrisma.prisma = prisma;
}
+10
View File
@@ -0,0 +1,10 @@
export default function GlobalLoading() {
return (
<div className="min-h-[50vh] flex items-center justify-center">
<div className="text-center">
<span className="loading loading-spinner loading-lg text-primary"></span>
<p className="mt-4 text-base-content/70">Loading...</p>
</div>
</div>
);
}
+19
View File
@@ -0,0 +1,19 @@
interface PageProps {
params: Promise<{ id: string }>;
}
const NewsletterDetailPage = async ({ params }: PageProps) => {
const { id } = await params;
return (
<div className="text-center">
<h1 className="font-bold text-center text-amber-900 tracking-tight mt-2 text-3xl">
Newsletter Page
</h1>
<h2 className="text-center text-fuchsia-600 mt-2"> ID requested {id} </h2>
<p className="mt-5">Your implementation goes here </p>
</div>
);
};
export default NewsletterDetailPage;
+14
View File
@@ -0,0 +1,14 @@
"use client";
const NewslettersPage = () => {
return (
<div className="text-center">
<h1 className="font-bold text-center text-amber-900 tracking-tight mt-2 text-3xl">
Newsletters Page
</h1>
<p className="mt-5">Your implementation goes here </p>
</div>
);
};
export default NewslettersPage;
+23
View File
@@ -0,0 +1,23 @@
import Link from "next/link";
export default function NotFound() {
return (
<div className="min-h-[50vh] flex items-center justify-center p-4">
<div className="text-center">
<div className="text-8xl font-bold text-primary mb-4">404</div>
<h2 className="text-2xl font-bold mb-2">Page Not Found</h2>
<p className="text-base-content/70 mb-6">
The page you&apos;re looking for doesn&apos;t exist or has been moved.
</p>
<div className="flex gap-4 justify-center">
<Link href="/" className="btn btn-primary">
Go Home
</Link>
<Link href="/skills" className="btn btn-ghost">
Browse Skills
</Link>
</div>
</div>
</div>
);
}
+65
View File
@@ -0,0 +1,65 @@
import Image from "next/image";
export default function Home() {
return (
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the page.tsx file.
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
</p>
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
<a
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={16}
height={16}
/>
Deploy Now
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Documentation
</a>
</div>
</main>
</div>
);
}
+39
View File
@@ -0,0 +1,39 @@
"use client";
import type { Result } from "./person";
interface PersonItemProps extends Result {
remove: (uuid: string) => void;
}
const PersonItem = ({ remove, ...result }: PersonItemProps) => {
const { email, login, location, name, picture } = result;
return (
<div className="card bg-base-200 w-96 shadow-sm" key={login.uuid}>
<figure className="px-10 pt-10">
<img src={picture.medium} alt={name.last} className="rounded-sm" />
</figure>
<div className="card-body items-center text-center">
<h2 className="card-title sm:text-sm md:text-lg lg:text-xl">
{name.first} {name.last}
</h2>
<h4>{email}</h4>
<p className="sm:text-sm md:text-md lg:text-lg">
{location.city}, {location.country}
</p>
<div className="card-actions">
<button
className="btn btn-active btn-accent btn-xs sm:btn-sm md:btn-md lg:btn-lg xl:btn-xl"
onClick={() => remove(login.uuid)}
>
{" "}
remove{" "}
</button>
</div>
</div>
</div>
);
};
export default PersonItem;
+62
View File
@@ -0,0 +1,62 @@
"use client";
import axios from "axios";
import type { Result } from "./person";
import PersonItem from "./PersonItem";
import { useEffect, useState } from "react";
import { toast } from "react-hot-toast";
const url = "https://randomuser.me/api/?results=12";
const PeoplePage = () => {
const [users, setUsers] = useState<Result[]>([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
axios
.get(url)
.then((response) => {
console.log(response);
setUsers(response.data.results);
setIsLoading(false);
})
.catch((error: any) => {
if (error.isAxiosError) {
console.log(error.response);
toast.error(`Error occurred while fetching..`);
} else {
console.log(error);
}
});
}, []);
if (isLoading) {
return (
<>
<span className="loading loading-ball loading-xs"></span>
<span className="loading loading-ball loading-sm"></span>
<span className="loading loading-ball loading-md"></span>
<span className="loading loading-ball loading-lg"></span>
<span className="loading loading-ball loading-xl"></span>
</>
);
}
return (
<section>
<h2 className="font-bold text-center text-amber-900 tracking-tight mt-2 text-3xl">
People Page
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 p-6">
{users?.map((user) => {
return (
<PersonItem {...user} key={user.login.uuid} remove={() => {}} />
);
})}
</div>
</section>
);
};
export default PeoplePage;
+71
View File
@@ -0,0 +1,71 @@
"use client";
import type { Result } from "./person";
import PersonItem from "./PersonItem";
import { useEffect, useState } from "react";
import {
fetchRandomUsers,
clearList,
removeUser,
} from "@/lib/features/people/personSlice";
import { useAppSelector, useAppDispatch, useAppStore } from "../../lib/hooks";
const PeoplePage = () => {
const { results, isLoading } = useAppSelector((store) => store.people);
const dispatch = useAppDispatch();
useEffect(() => {
dispatch(fetchRandomUsers());
}, []);
const handleClearList = () => {
dispatch(clearList());
};
const reset = () => {
dispatch(fetchRandomUsers());
};
const remove = (id: any) => {
dispatch(removeUser(id));
};
if (isLoading) {
return (
<div className="p-6 max-w-md mx-auto my-4">
{" "}
<span className="loading loading-spinner loading-sm"></span>
</div>
);
}
return (
<section>
<h2 className="font-bold text-center text-amber-900 tracking-tight mt-2 text-3xl">
People Page
</h2>
<div className="flex items-center justify-center mt-5">
{results?.length < 1 ? (
<button className="btn btn-soft" onClick={reset}>
reset
</button>
) : (
<button className="btn btn-soft" onClick={handleClearList}>
Clear All
</button>
)}
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 p-6">
{results?.map((p: Result) => {
return <PersonItem {...p} key={p.login.uuid} remove={remove} />;
})}
</div>
</section>
);
};
export default PeoplePage;
+86
View File
@@ -0,0 +1,86 @@
interface RootObject {
results: Result[];
info: Info;
}
interface Info {
seed: string;
results: number;
page: number;
version: string;
}
interface Result {
content: React.ReactNode;
gender: string;
name: Name;
location: Location;
email: string;
login: Login;
dob: Dob;
registered: Dob;
phone: string;
cell: string;
id: Id;
picture: Picture;
nat: string;
}
interface Picture {
large: string;
medium: string;
thumbnail: string;
}
interface Id {
name: string;
value: null | string;
}
interface Dob {
date: string;
age: number;
}
interface Login {
uuid: string;
username: string;
password: string;
salt: string;
md5: string;
sha1: string;
sha256: string;
}
interface Location {
street: Street;
city: string;
state: string;
country: string;
postcode: number | string;
coordinates: Coordinates;
timezone: Timezone;
}
interface Timezone {
offset: string;
description: string;
}
interface Coordinates {
latitude: string;
longitude: string;
}
interface Street {
number: number;
name: string;
}
interface Name {
title: string;
first: string;
last: string;
}
export type { Result, Name, Picture, Location, Login };
+89
View File
@@ -0,0 +1,89 @@
"use client";
import { useActionState, JSX } from "react";
import { addUserAction, FormState } from "../actions/UserActionsZod";
import SubmitButton from "./SubmitButton";
const initialState: FormState = {
success: false,
message: "",
};
export default function AddUserForm(): JSX.Element {
// useActionState receives (action, initialState)
const [state, formAction] = useActionState(addUserAction, initialState);
return (
<div className="card bg-base-100 shadow border border-base-300">
<div className="card-body">
<h2 className="card-title text-lg">
Add New User using Zod Validation
</h2>
{/* Global Success / Failure Alerts */}
{state.message && (
<div
className={`alert ${state.success ? "alert-success" : "alert-error"} text-sm py-2`}
>
<span>{state.message}</span>
</div>
)}
<form action={formAction} className="space-y-4 mt-2">
{/* Name Input */}
<div className="form-control">
<label className="label label-text font-medium">Name</label>
<input
type="text"
name="name"
placeholder="Jane Doe"
className={`input input-bordered w-full ${state.errors?.name ? "input-error" : ""}`}
/>
{state.errors?.name && (
<span className="text-xs text-error mt-1">
{state.errors.name[0]}
</span>
)}
</div>
{/* Email Input */}
<div className="form-control">
<label className="label label-text font-medium">Email</label>
<input
type="email"
name="email"
placeholder="jane@example.com"
className={`input input-bordered w-full ${state.errors?.email ? "input-error" : ""}`}
/>
{state.errors?.email && (
<span className="text-xs text-error mt-1">
{state.errors.email[0]}
</span>
)}
</div>
{/* Password Input */}
<div className="form-control">
<label className="label label-text font-medium">Password</label>
<input
type="password"
name="pass"
placeholder="••••••••"
className={`input input-bordered w-full ${state.errors?.pass ? "input-error" : ""}`}
/>
{state.errors?.pass && (
<span className="text-xs text-error mt-1">
{state.errors.pass[0]}
</span>
)}
</div>
{/* Submit Button with Loading Spinner */}
<div className="flex justify-end pt-2">
<SubmitButton label="Create Account" />
</div>
</form>
</div>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
"use client";
import { JSX } from "react";
import { useFormStatus } from "react-dom";
export default function SubmitButton({
label = "Add User",
}: {
label?: string;
}): JSX.Element {
const { pending } = useFormStatus();
return (
<button
type="submit"
disabled={pending}
className="btn btn-primary w-full md:w-auto"
>
{pending ? (
<>
<span className="loading loading-spinner loading-xs"></span>
Saving...
</>
) : (
label
)}
</button>
);
}
+140
View File
@@ -0,0 +1,140 @@
import { JSX } from "react";
import { getUsers, addUser, editUser, removeUser } from "../actions/UserAction";
import AddUserForm from "./AddUserForm";
export default async function UsersPage(): Promise<JSX.Element> {
const users = await getUsers();
return (
<main className="min-h-screen bg-base-200 p-8 flex flex-col items-center">
<div className="max-w-4xl w-full space-y-6">
<h1 className="text-3xl font-bold">PostgreSQL User Management</h1>
{/* add user form using zod validation */}
<AddUserForm />
{/* --- ADD USER FORM --- */}
<div className="card bg-base-100 shadow border border-base-300">
<div className="card-body">
<h2 className="card-title text-lg">Add New User</h2>
{/* Form using Server Action */}
<form
action={async (formData: FormData) => {
"use server";
const name = formData.get("name") as string;
const email = formData.get("email") as string;
const pass = formData.get("pass") as string;
if (name && email && pass) {
await addUser({ name, email, pass });
}
}}
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"
required
/>
<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>
</div>
</div>
{/* --- USER TABLE --- */}
<div className="card bg-base-100 shadow border border-base-300">
<div className="card-body p-0">
<div className="overflow-x-auto">
<table className="table table-zebra w-full">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
<th className="text-right">Actions</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>
<td className="font-mono">{user.id}</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td className="font-mono text-xs opacity-60">
{user.password}
</td>
<td className="text-right flex justify-end gap-2">
{/* EDIT BUTTON (QUICK NAME UPDATE) */}
<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>
{/* DELETE BUTTON */}
<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 && (
<tr>
<td
colSpan={5}
className="text-center py-4 text-base-content/60"
>
No users found in database. Add one above!
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
</div>
</main>
);
}