From 4e96d7cbed40731fa35bb8f9f24cbabd032d4651 Mon Sep 17 00:00:00 2001 From: OKAMOTO Shigehiro Date: Thu, 25 Apr 2024 16:54:31 +0900 Subject: [PATCH] =?UTF-8?q?=E3=83=95=E3=82=A9=E3=83=BC=E3=83=A0=E3=81=8B?= =?UTF-8?q?=E3=82=89=E9=9B=A2=E8=84=B1=E6=99=82=E3=81=AB=E3=83=97=E3=83=AD?= =?UTF-8?q?=E3=83=B3=E3=83=97=E3=83=88=E3=82=92=E8=A1=A8=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/common_components/form_answer/Form.tsx | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/common_components/form_answer/Form.tsx b/src/common_components/form_answer/Form.tsx index 312b24b8..f420781c 100644 --- a/src/common_components/form_answer/Form.tsx +++ b/src/common_components/form_answer/Form.tsx @@ -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"; @@ -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 = async (data) => { if (Array.from(fileErrors).some((v) => v[1])) { toast.error(`正しいファイルをアップロードしてください`); @@ -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 () => { @@ -115,6 +132,7 @@ export const Form = ({ form, answerId, answerItems, editable }: Props) => { return; } toast.success("申請の送信に成功しました"); + window.removeEventListener("beforeunload", handleBeforeunload); window.location.reload(); }) .catch(async () => {