Spaces:
Sleeping
Sleeping
File size: 2,738 Bytes
241884b 445f8f2 241884b 445f8f2 241884b 445f8f2 241884b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
"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>
);
}
|