Skip to content

Commit 09e5f70

Browse files
authored
Merge pull request #10 from database-playground/pan93412/dbp-18-修正「防止編輯被意外打斷」modal-沒有正確彈出的問題
fix: unsaved warning for MeForm
2 parents 13bfec9 + 9dad902 commit 09e5f70

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

app/(admin)/me/_components/form.tsx

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@ import AppAvatar from "@/components/avatar";
44
import { Button } from "@/components/ui/button";
55
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
66
import { Input } from "@/components/ui/input";
7-
import { useFormDirtyWarning } from "@/hooks/use-form-dirty-warning";
87
import { BASIC_USER_INFO_QUERY } from "@/lib/user";
98
import { useUser } from "@/providers/use-user";
109
import { useMutation } from "@apollo/client/react";
1110
import { zodResolver } from "@hookform/resolvers/zod";
11+
import { useEffect } from "react";
1212
import { useForm } from "react-hook-form";
1313
import { toast } from "sonner";
1414
import { z } from "zod";
@@ -30,7 +30,23 @@ export function MeForm() {
3030
},
3131
});
3232

33-
useFormDirtyWarning(form.formState.isDirty);
33+
useEffect(() => {
34+
const message = "您有尚未儲存的更動。確定要關閉而不儲存嗎?您的更動將會遺失。";
35+
36+
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
37+
if (!form.formState.isDirty) return;
38+
39+
e.preventDefault();
40+
e.returnValue = message;
41+
return message;
42+
};
43+
44+
window.addEventListener("beforeunload", handleBeforeUnload);
45+
46+
return () => {
47+
window.removeEventListener("beforeunload", handleBeforeUnload);
48+
};
49+
}, [form]);
3450

3551
const avatar = form.watch("avatar");
3652

0 commit comments

Comments
 (0)