🗂
【Drizzle ORM】NextJs14 と Drizzle ORM【#33 Profile Update Form】
【#33 Profile Update Form】
YouTube: https://youtu.be/JWQANfe5MX8
今回はプロフィールのアップデート用のフォームを作成します。
まずは、プロフィールの「id」を取得するために、
「"/me"」のルートの「columns」に
「id」を追加して、「true」を設定します。
app/api/[[...route]]/user.ts
import { Hono } from "hono";
import { z } from "zod";
import { zValidator } from "@hono/zod-validator";
import { clerkMiddleware, getAuth } from "@hono/clerk-auth";
import { db } from "@/db/drizzle";
import { profile, users } from "@/db/schema";
import { eq } from "drizzle-orm";
const app = new Hono()
.get("/", async (c) => {
const data = await db.select().from(users);
return c.json({
data,
});
})
.get("/me", clerkMiddleware(), async (c) => {
const auth = getAuth(c);
if (!auth?.userId) {
return c.json({ error: "Unauthorized" }, 401);
}
// const [data] = await db
// .select()
// .from(users)
// .leftJoin(profile, eq(users.id, profile.userId))
// .where(eq(users.clerkId, auth.userId));
const data = await db.query.users.findFirst({
where: eq(users.clerkId, auth.userId),
with: {
profile: {
columns: {
id: true,
message: true,
},
},
},
});
if (!data) {
return c.json({ error: "User not found" }, 404);
}
return c.json({ data });
})
.get(
"/:id",
zValidator(
"param",
z.object({
id: z.string(),
})
),
async (c) => {
// const id = c.req.param("id");
const { id } = c.req.valid("param");
const [data] = await db.select().from(users).where(eq(users.id, id));
if (!data) {
return c.json({ error: "User not found" }, 404);
}
// if (data.length === 0) {
// return c.json({ error: "User not found" }, 404);
// }
return c.json({
user: data,
});
}
);
export default app;
app/(protected)/profile/page.tsx
"use client";
import { useState, useRef, ElementRef } from "react";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { useCreateProfile } from "@/hooks/profiles/use-create-profile";
import { useGetClerkUser } from "@/hooks/users/use-get-clerk-user";
import { useUpdateProfile } from "@/hooks/profiles/use-update-profile";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormMessage,
} from "@/components/ui/form";
import { Textarea } from "@/components/ui/textarea";
const formSchema = z.object({
message: z.string().min(2, {
message: "Message must be at least 2 characters.",
}),
});
const ProfilePage = () => {
const [isEditable, setIsEditable] = useState(false);
const formRef = useRef<ElementRef<"form">>(null);
const textareaRef = useRef<ElementRef<"textarea">>(null);
const { mutate, isPending } = useCreateProfile();
const { mutate: updateMutate, isPending: updateIsPending } =
useUpdateProfile();
const clerkUserQuery = useGetClerkUser();
const clerkUser = clerkUserQuery.data;
const isLoading = clerkUserQuery.isLoading;
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
message: "",
},
});
const onSubmit = (values: z.infer<typeof formSchema>) => {
if (clerkUser && clerkUser.profile && clerkUser.profile.message) {
updateMutate({ id: clerkUser.profile.id, message: values.message });
} else {
mutate(values);
}
};
const enableEditing = () => {
if (clerkUser && clerkUser.profile && clerkUser.profile.message) {
form.setValue("message", clerkUser.profile.message);
}
setIsEditable(true);
setTimeout(() => {
textareaRef.current?.focus();
textareaRef.current?.select();
});
};
const onBlur = () => {
formRef.current?.requestSubmit();
setIsEditable(false);
};
if (isLoading || !clerkUser) {
return <div>Loading...</div>;
}
return (
<div className="flex flex-col gap-y-3">
<Card>
<CardHeader>
<CardTitle className="font-bold">My Profile</CardTitle>
<CardDescription>Profile Details</CardDescription>
<Separator className="my-4" />
</CardHeader>
<CardContent>
<div className="flex items-center gap-x-2">
<Avatar>
<AvatarImage src={clerkUser.imageUrl || ""} alt="User" />
<AvatarFallback>M</AvatarFallback>
</Avatar>
<div className="flex flex-col justify-center">
<p className="text-sm truncate">{clerkUser.name}</p>
<p className="text-sm truncate text-muted-foreground">
{clerkUser.email}
</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="font-bold">Message</CardTitle>
<CardDescription>Profile Message</CardDescription>
<Separator className="my-4" />
</CardHeader>
<CardContent>
{isEditable ? (
<div>
<Form {...form}>
<form ref={formRef} onSubmit={form.handleSubmit(onSubmit)}>
<FormField
control={form.control}
name="message"
render={({ field }) => (
<FormItem>
<FormControl>
<Textarea
placeholder="Hello"
{...field}
onBlur={onBlur}
ref={textareaRef}
className="w-full h-40 resize-none rounded-md"
disabled={isPending}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</div>
) : !clerkUser.profile ? (
<Button onClick={enableEditing}>Create Message</Button>
) : (
<div
onClick={enableEditing}
className="w-full h-40 p-3 text-sm rounded-lg border-2 border-gray-600"
>
{clerkUser.profile.message}
</div>
)}
</CardContent>
</Card>
</div>
);
};
export default ProfilePage;
今回条件分岐で設定している部分ですが、
「 (clerkUser && clerkUser.profile && clerkUser.profile.message) 」
こちらはフォームの部分を別のコンポーネントに切り分けて、
「clerkUser.profile」をpropsとして受け取る形で作成すると、
ここまで長い条件分岐は不要になるかと思います。
また、
「form.setValue("message", clerkUser.profile.message)」
の部分も、propsで受け取った値を
useFormで作成したdefaultValuesのデフォルト値に
設定することで省略できるかと思います。
Discussion