feat: implement EditProfile functionality with form validation and update user profile API integration

This commit is contained in:
2025-09-06 20:22:40 +02:00
parent fc7dacc6fb
commit 19520c832f
6 changed files with 345 additions and 17 deletions

View File

@@ -1,6 +1,6 @@
// app/page.tsx
import { cookies } from "next/headers";
import { getFeed, getUserProfile } from "@/lib/api";
import { getFeed, getMe, getUserProfile, Me } from "@/lib/api";
import { ThoughtCard } from "@/components/thought-card";
import { PostThoughtForm } from "@/components/post-thought-form";
import { Button } from "@/components/ui/button";
@@ -20,6 +20,7 @@ export default async function Home() {
async function FeedPage({ token }: { token: string }) {
const feedData = await getFeed(token);
const me = (await getMe(token).catch(() => null)) as Me | null;
const authors = [...new Set(feedData.thoughts.map((t) => t.authorUsername))];
const userProfiles = await Promise.all(
authors.map((username) => getUserProfile(username, token).catch(() => null))
@@ -46,6 +47,7 @@ async function FeedPage({ token }: { token: string }) {
username: thought.authorUsername,
avatarUrl: authorDetails.get(thought.authorUsername)?.avatarUrl,
}}
currentUser={me}
/>
))}
{feedData.thoughts.length === 0 && (

View File

@@ -0,0 +1,39 @@
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { getMe } from "@/lib/api";
import {
Card,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import { EditProfileForm } from "@/components/edit-profile-form";
// This is a Server Component to fetch initial data
export default async function EditProfilePage() {
const token = (await cookies()).get("auth_token")?.value;
if (!token) {
redirect("/login");
}
const me = await getMe(token).catch(() => null);
if (!me) {
redirect("/login");
}
return (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Edit Profile</CardTitle>
<CardDescription>
Update your public profile information.
</CardDescription>
</CardHeader>
<EditProfileForm currentUser={me} />
</Card>
</div>
);
}

View File

@@ -1,4 +1,4 @@
import { getMe, getUserProfile, getUserThoughts } from "@/lib/api";
import { getMe, getUserProfile, getUserThoughts, Me } from "@/lib/api";
import { UserAvatar } from "@/components/user-avatar";
import { ThoughtCard } from "@/components/thought-card";
import { Calendar } from "lucide-react";
@@ -35,7 +35,7 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
const user = userResult.value;
const thoughts =
thoughtsResult.status === "fulfilled" ? thoughtsResult.value.thoughts : [];
const me = meResult.status === "fulfilled" ? meResult.value : null;
const me = meResult.status === "fulfilled" ? (meResult.value as Me) : null;
// *** SIMPLIFIED LOGIC ***
// The follow status is now directly available from the `me` object.
@@ -104,6 +104,7 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
key={thought.id}
thought={thought}
author={{ username: user.username, avatarUrl: user.avatarUrl }}
currentUser={me || null}
/>
))}
{thoughts.length === 0 && (

View File

@@ -0,0 +1,172 @@
"use client";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useRouter } from "next/navigation";
import { useAuth } from "@/hooks/use-auth";
import { Me, UpdateProfileSchema, updateProfile } from "@/lib/api";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardFooter } from "@/components/ui/card";
import {
Form,
FormField,
FormItem,
FormLabel,
FormControl,
FormMessage,
FormDescription,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
interface EditProfileFormProps {
currentUser: Me;
}
export function EditProfileForm({ currentUser }: EditProfileFormProps) {
const router = useRouter();
const { token } = useAuth();
const form = useForm<z.infer<typeof UpdateProfileSchema>>({
resolver: zodResolver(UpdateProfileSchema),
defaultValues: {
displayName: currentUser.displayName ?? undefined,
bio: currentUser.bio ?? undefined,
avatarUrl: currentUser.avatarUrl ?? undefined,
headerUrl: currentUser.headerUrl ?? undefined,
customCss: currentUser.customCss ?? undefined,
topFriends: currentUser.topFriends ?? [],
},
});
async function onSubmit(values: z.infer<typeof UpdateProfileSchema>) {
if (!token) return;
toast.info("Updating your profile...");
try {
await updateProfile(values, token);
toast.success("Profile updated successfully!");
// Redirect to the profile page to see the changes
router.push(`/users/${currentUser.username}`);
router.refresh(); // Ensure fresh data is loaded
} catch (err) {
toast.error("Failed to update profile.");
}
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<Card>
<CardContent className="space-y-6 pt-6">
<FormField
name="displayName"
control={form.control}
render={({ field }) => (
<FormItem>
<FormLabel>Display Name</FormLabel>
<FormControl>
<Input placeholder="Your display name" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
name="bio"
control={form.control}
render={({ field }) => (
<FormItem>
<FormLabel>Bio</FormLabel>
<FormControl>
<Textarea placeholder="Tell us about yourself" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
name="avatarUrl"
control={form.control}
render={({ field }) => (
<FormItem>
<FormLabel>Avatar URL</FormLabel>
<FormControl>
<Input
placeholder="https://example.com/avatar.png"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
name="headerUrl"
control={form.control}
render={({ field }) => (
<FormItem>
<FormLabel>Header URL</FormLabel>
<FormControl>
<Input
placeholder="https://example.com/header.jpg"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
name="customCss"
control={form.control}
render={({ field }) => (
<FormItem>
<FormLabel>Custom CSS</FormLabel>
<FormControl>
<Textarea
placeholder="body { font-family: 'Comic Sans MS'; }"
rows={5}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
name="topFriends"
control={form.control}
render={({ field }) => (
<FormItem>
<FormLabel>Top Friends</FormLabel>
<FormControl>
<Input
placeholder="username1, username2, ..."
{...field}
onChange={(e) =>
field.onChange(
e.target.value.split(",").map((s) => s.trim())
)
}
/>
</FormControl>
<FormDescription>
A comma-separated list of usernames.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</CardContent>
<CardFooter className="border-t px-6 py-4">
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? "Saving..." : "Save Changes"}
</Button>
</CardFooter>
</Card>
</form>
</Form>
);
}

View File

@@ -1,7 +1,30 @@
"use client";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { UserAvatar } from "./user-avatar";
import { Thought } from "@/lib/api";
import { deleteThought, Me, Thought } from "@/lib/api";
import { formatDistanceToNow } from "date-fns";
import { useAuth } from "@/hooks/use-auth";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { MoreHorizontal, Trash2 } from "lucide-react";
interface ThoughtCardProps {
thought: Thought;
@@ -9,25 +32,85 @@ interface ThoughtCardProps {
username: string;
avatarUrl?: string | null;
};
currentUser: Me | null;
}
export function ThoughtCard({ thought, author }: ThoughtCardProps) {
export function ThoughtCard({
thought,
author,
currentUser,
}: ThoughtCardProps) {
const [isAlertOpen, setIsAlertOpen] = useState(false);
const { token } = useAuth();
const router = useRouter();
const timeAgo = formatDistanceToNow(new Date(thought.createdAt), {
addSuffix: true,
});
const isAuthor = currentUser?.username === thought.authorUsername;
const handleDelete = async () => {
if (!token) return;
try {
await deleteThought(thought.id, token);
toast.success("Thought deleted successfully.");
router.refresh(); // Refresh the feed
} catch (error) {
toast.error("Failed to delete thought.");
} finally {
setIsAlertOpen(false);
}
};
return (
<Card>
<CardHeader className="flex flex-row items-center gap-4 space-y-0">
<UserAvatar src={author.avatarUrl} alt={author.username} />
<div className="flex flex-col">
<span className="font-bold">{author.username}</span>
<span className="text-sm text-muted-foreground">{timeAgo}</span>
</div>
</CardHeader>
<CardContent>
<p className="whitespace-pre-wrap break-words">{thought.content}</p>
</CardContent>
</Card>
<>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0">
<div className="flex items-center gap-4">
<UserAvatar src={author.avatarUrl} alt={author.username} />
<div className="flex flex-col">
<span className="font-bold">{author.username}</span>
<span className="text-sm text-muted-foreground">{timeAgo}</span>
</div>
</div>
{isAuthor && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="p-2 rounded-full hover:bg-accent">
<MoreHorizontal className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem
className="text-destructive"
onSelect={() => setIsAlertOpen(true)}
>
<Trash2 className="mr-2 h-4 w-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</CardHeader>
<CardContent>
<p className="whitespace-pre-wrap break-words">{thought.content}</p>
</CardContent>
</Card>
<AlertDialog open={isAlertOpen} onOpenChange={setIsAlertOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you sure?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently delete your
thought.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleDelete}>Delete</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}

View File

@@ -51,6 +51,15 @@ export const CreateThoughtSchema = z.object({
replyToId: z.string().uuid().optional(),
});
export const UpdateProfileSchema = z.object({
displayName: z.string().max(50).optional(),
bio: z.string().max(160).optional(),
avatarUrl: z.url().or(z.literal("")).optional(),
headerUrl: z.url().or(z.literal("")).optional(),
customCss: z.string().optional(),
topFriends: z.array(z.string()).max(8).optional(),
});
export type User = z.infer<typeof UserSchema>;
export type Me = z.infer<typeof MeSchema>;
export type Thought = z.infer<typeof ThoughtSchema>;
@@ -161,4 +170,26 @@ export const unfollowUser = (username: string, token: string) =>
"/tags/popular",
{},
z.array(z.string()) // Expect an array of strings
);
export const deleteThought = (thoughtId: string, token: string) =>
apiFetch(
`/thoughts/${thoughtId}`,
{ method: "DELETE" },
z.null(), // Expect a 204 No Content response
token
);
export const updateProfile = (
data: z.infer<typeof UpdateProfileSchema>,
token: string
) =>
apiFetch(
"/users/me",
{
method: "PUT",
body: JSON.stringify(data),
},
UserSchema, // Expect the updated user object back
token
);