Skip to content

Commit 3acfaaa

Browse files
committed
fix: confirmation modal not working
1 parent 516d7f0 commit 3acfaaa

File tree

3 files changed

+29
-36
lines changed

3 files changed

+29
-36
lines changed

components/update-modal/form-body.tsx

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { Button } from "@/components/ui/button";
22
import { DialogFooter } from "@/components/ui/dialog";
33
import { Form } from "@/components/ui/form";
4-
import { useFormDirtyWarning } from "@/hooks/use-form-dirty-warning";
54
import React, { useEffect } from "react";
65
import { type FieldValues, type SubmitHandler, type UseFormReturn } from "react-hook-form";
76

@@ -21,12 +20,18 @@ export function UpdateFormBody<T extends FieldValues>({
2120
onFormStateChange,
2221
children,
2322
}: UpdateFormBodyProps<T>) {
24-
useFormDirtyWarning(form.formState.isDirty);
25-
26-
// Notify parent component about form dirty state changes
2723
useEffect(() => {
28-
onFormStateChange?.(form.formState.isDirty);
29-
}, [form.formState.isDirty, onFormStateChange]);
24+
const unsubscribe = form.subscribe({
25+
formState: {
26+
isDirty: true,
27+
},
28+
callback: (data) => {
29+
onFormStateChange?.(data.isDirty ?? false);
30+
},
31+
})
32+
33+
return () => unsubscribe();
34+
}, [form, onFormStateChange]);
3035

3136
const handleSubmit = (data: T) => {
3237
form.reset();

hooks/use-dialog-close-confirmation.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useCallback, useState } from "react";
1+
import { useCallback, useEffect, useState } from "react";
22

33
export interface UseDialogCloseConfirmationOptions {
44
isDirty: boolean;
@@ -13,6 +13,23 @@ export function useDialogCloseConfirmation({
1313
}: UseDialogCloseConfirmationOptions) {
1414
const [showConfirmation, setShowConfirmation] = useState(false);
1515

16+
useEffect(() => {
17+
const message = "您有尚未儲存的更動。確定要關閉而不儲存嗎?您的更動將會遺失。";
18+
if (!isDirty) return;
19+
20+
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
21+
e.preventDefault();
22+
e.returnValue = message;
23+
return message;
24+
};
25+
26+
window.addEventListener("beforeunload", handleBeforeUnload);
27+
28+
return () => {
29+
window.removeEventListener("beforeunload", handleBeforeUnload);
30+
};
31+
}, [isDirty])
32+
1633
const handleDialogOpenChange = useCallback(
1734
(newOpen: boolean) => {
1835
// If trying to close the dialog and form is dirty

hooks/use-form-dirty-warning.ts

Lines changed: 0 additions & 29 deletions
This file was deleted.

0 commit comments

Comments
 (0)