Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 25 additions & 10 deletions web/hooks/use-reload-confirmation.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,41 @@
import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/router";

const useReloadConfirmations = (message?: string) => {
//TODO: remove temp flag isActive later and use showAlert as the source of truth
const useReloadConfirmations = (isActive = true) => {
const [showAlert, setShowAlert] = useState(false);
const router = useRouter();

const handleBeforeUnload = useCallback(
(event: BeforeUnloadEvent) => {
if (!isActive || !showAlert) return;
event.preventDefault();
event.returnValue = "";
return message ?? "Are you sure you want to leave?";
},
[message]
[isActive, showAlert]
);

useEffect(() => {
if (!showAlert) {
window.removeEventListener("beforeunload", handleBeforeUnload);
return;
}
const handleRouteChangeStart = useCallback(
(url: string) => {
if (!isActive || !showAlert) return;
const leave = confirm("Are you sure you want to leave? Changes you made may not be saved.");
if (!leave) {
router.events.emit("routeChangeError");
throw `Route change to "${url}" was aborted (this error can be safely ignored).`;
}
},
[isActive, showAlert, router.events]
);

useEffect(() => {
window.addEventListener("beforeunload", handleBeforeUnload);
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, [handleBeforeUnload, showAlert]);
router.events.on("routeChangeStart", handleRouteChangeStart);

return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
router.events.off("routeChangeStart", handleRouteChangeStart);
};
}, [handleBeforeUnload, handleRouteChangeStart, router.events]);

return { setShowAlert };
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,6 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {
// toast alert
const { setToastAlert } = useToast();

//TODO:fix reload confirmations, with mobx
const { setShowAlert } = useReloadConfirmations();

const { handleSubmit, setValue, watch, getValues, control, reset } = useForm<IPage>({
defaultValues: { name: "", description_html: "" },
});
Expand Down Expand Up @@ -89,6 +86,8 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {

const pageStore = usePage(pageId as string);

const { setShowAlert } = useReloadConfirmations(pageStore?.isSubmitting === "submitting");

useEffect(
() => () => {
if (pageStore) {
Expand Down