From 062dae1dbc18cf1afe1a13aaecb6108e95b2fe05 Mon Sep 17 00:00:00 2001 From: Eric Ge Date: Mon, 31 Mar 2025 21:25:00 -0400 Subject: [PATCH] add profile edit page --- compass/app/profile/edit/page.tsx | 187 ++++++++++++++++++++++++++++++ 1 file changed, 187 insertions(+) create mode 100644 compass/app/profile/edit/page.tsx diff --git a/compass/app/profile/edit/page.tsx b/compass/app/profile/edit/page.tsx new file mode 100644 index 0000000..983992c --- /dev/null +++ b/compass/app/profile/edit/page.tsx @@ -0,0 +1,187 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import User from "@/utils/models/User"; +import { Program, Role } from "@/utils/models/User"; +import { createClient } from "@/utils/supabase/client"; + +export default function EditProfile() { + const router = useRouter(); + const [user, setUser] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [success, setSuccess] = useState(false); + + useEffect(() => { + const fetchUser = async () => { + try { + const supabase = await createClient(); + const { data: { user: authUser }, error: authError } = await supabase.auth.getUser(); + + if (authError || !authUser) { + throw new Error("Authentication required"); + } + + const response = await fetch(`/api/user?uuid=${authUser.id}`); + if (!response.ok) { + throw new Error("Failed to fetch user data"); + } + const currentUser = await response.json(); + + if (!currentUser) { + throw new Error("User not found"); + } + + setUser(currentUser); + } catch (err) { + setError("Failed to load user data"); + console.error(err); + } finally { + setLoading(false); + } + }; + + fetchUser(); + }, []); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + if (!user) return; + + try { + const formData = new FormData(e.currentTarget); + const updatedUser = { + ...user, + username: formData.get("username") as string, + email: formData.get("email") as string, + group: formData.get("group") as string, + experience: parseInt(formData.get("experience") as string), + program: formData.getAll("program") as Program[], + }; + + const response = await fetch(`/api/user/update?uuid=${user.uuid}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(updatedUser), + }); + + if (!response.ok) { + throw new Error("Failed to update profile"); + } + + setSuccess(true); + } catch (err) { + setError("Failed to update profile"); + console.error(err); + } + }; + + if (loading) { + return
Loading...
; + } + + if (!user) { + return
User not found
; + } + + return ( +
+

Edit Profile

+ + {error && ( +
+ {error} +
+ )} + + {success && ( +
+ Profile updated successfully! Refreshing page... +
+ )} + +
+
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ +
+ {Object.values(Program).map((program) => ( + + ))} +
+
+ +
+ + +
+
+
+ ); +} \ No newline at end of file