Spaces:
Sleeping
Sleeping
"use client"; | |
import { zodResolver } from "@hookform/resolvers/zod"; | |
import { useForm, SubmitHandler } from "react-hook-form"; | |
import { z } from "zod"; | |
import { Input } from "./ui/input"; | |
import { Button } from "./ui/button"; | |
import { Label } from "./ui/label"; | |
import { useState } from "react"; | |
import { createClient } from "@/utils/supabase/client"; | |
import { useRouter } from "next/navigation"; | |
const schema = z | |
.object({ | |
password: z.string().min(8, "Password minimal 8 karakter"), | |
confirm: z.string().min(8, "Konfirmasi minimal 8 karakter"), | |
}) | |
.refine((data) => data.password === data.confirm, { | |
message: "Password dan konfirmasi tidak sama", | |
path: ["confirm"], | |
}); | |
type FormFields = z.infer<typeof schema>; | |
export default function ResetPasswordForm() { | |
const supabase = createClient(); | |
const router = useRouter(); | |
const [successMsg, setSuccessMsg] = useState<string | null>(null); | |
const { | |
register, | |
handleSubmit, | |
setError, | |
formState: { errors, isSubmitting }, | |
} = useForm<FormFields>({ resolver: zodResolver(schema) }); | |
const onSubmit: SubmitHandler<FormFields> = async ({ password }) => { | |
setSuccessMsg(null); | |
const { error } = await supabase.auth.updateUser({ password }); | |
if (error) { | |
setError("root", { message: "Gagal mengubah password. Coba lagi." }); | |
return; | |
} | |
// Pastikan sesi lama tidak tersisa | |
await supabase.auth.signOut(); | |
// Opsi: tampilkan pesan singkat sebelum redirect | |
setSuccessMsg("Password berhasil diubah. Mengarahkan ke halaman login..."); | |
router.replace("/login"); | |
}; | |
return ( | |
<form className="flex flex-col gap-2" onSubmit={handleSubmit(onSubmit)}> | |
<Label htmlFor="password" className="text-left"> | |
Password Baru | |
</Label> | |
<Input id="password" type="password" placeholder="Password baru" {...register("password")} /> | |
{errors.password && ( | |
<div className="text-left text-xs text-red-500">{errors.password.message}</div> | |
)} | |
<Label htmlFor="confirm" className="text-left"> | |
Konfirmasi Password | |
</Label> | |
<Input id="confirm" type="password" placeholder="Konfirmasi password" {...register("confirm")} /> | |
{errors.confirm && ( | |
<div className="text-left text-xs text-red-500">{errors.confirm.message}</div> | |
)} | |
<Button disabled={isSubmitting} type="submit" className="mt-4 bg-orange-600 hover:bg-orange-800"> | |
{isSubmitting ? "Menyimpan..." : "Simpan Password"} | |
</Button> | |
{errors.root && ( | |
<div className="text-xs text-red-500">{errors.root.message}</div> | |
)} | |
{successMsg && ( | |
<div className="text-xs text-green-600">{successMsg}</div> | |
)} | |
</form> | |
); | |
} | |