Skip to content

Commit

Permalink
フォームから離脱時にプロンプトを表示
Browse files Browse the repository at this point in the history
  • Loading branch information
oka4shi committed Apr 25, 2024
1 parent e91b75f commit 4e96d7c
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/common_components/form_answer/Form.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { SubmitHandler, useForm } from "react-hook-form";
import { useState } from "react";
import { useCallback, useEffect, useState } from "react";
import { css } from "@styled-system/css";
import toast from "react-hot-toast";

Expand All @@ -20,6 +20,22 @@ interface Props {
}

export const Form = ({ form, answerId, answerItems, editable }: Props) => {
const handleBeforeunload = useCallback(
(event: BeforeUnloadEvent) => {
if (editable || !answerItems) {
event.preventDefault();
event.returnValue = "";
}
},
[answerItems, editable],
);
useEffect(() => {
window.addEventListener("beforeunload", handleBeforeunload);

return () => {
window.removeEventListener("beforeunload", handleBeforeunload);
};
}, [handleBeforeunload]);
const onSubmit: SubmitHandler<FormFieldsType> = async (data) => {
if (Array.from(fileErrors).some((v) => v[1])) {
toast.error(`正しいファイルをアップロードしてください`);
Expand Down Expand Up @@ -88,6 +104,7 @@ export const Form = ({ form, answerId, answerItems, editable }: Props) => {
await deleteAllUploadedFiles(fileIds);
throw new Error(error.message);
}
window.removeEventListener("beforeunload", handleBeforeunload);
window.location.reload();
})
.catch(async () => {
Expand Down Expand Up @@ -115,6 +132,7 @@ export const Form = ({ form, answerId, answerItems, editable }: Props) => {
return;
}
toast.success("申請の送信に成功しました");
window.removeEventListener("beforeunload", handleBeforeunload);
window.location.reload();
})
.catch(async () => {
Expand Down

0 comments on commit 4e96d7c

Please sign in to comment.