Skip to content

Commit

Permalink
chore: Handle back navigation when editing
Browse files Browse the repository at this point in the history
  • Loading branch information
SteveGT96 committed Jan 9, 2025
1 parent 2ba9d23 commit 2710930
Showing 1 changed file with 44 additions and 14 deletions.
58 changes: 44 additions & 14 deletions src/libraries/hooks/ui/useDiscardHelpers.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,12 @@
import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { useCallback, useEffect, useState } from "react";
import { useBlocker, useNavigate } from "react-router";

export function useDiscardHelpers() {
const { t } = useTranslation();
const navigate = useNavigate();

const [isBlocking, setIsBlocking] = useState(false);
const [isGoingBack, setIsGoingBack] = useState(false);
const [openCancelConfirmation, setOpenCancelConfirmation] = useState(false);
const handleCancelConfirmationDialog = useCallback(
(value: boolean) => () => {
setOpenCancelConfirmation(value);
if (isBlocking && !value) {
setIsBlocking(false);
blocker.reset?.();
}
},
[setOpenCancelConfirmation]
);

const blocker = useBlocker(function () {
if (openCancelConfirmation) {
Expand All @@ -28,15 +17,56 @@ export function useDiscardHelpers() {
return true;
});

const handleCancelConfirmationDialog = useCallback(
(value: boolean) => () => {
setOpenCancelConfirmation(value);
if (isBlocking && !value) {
setIsBlocking(false);
blocker.reset?.();
}
if (isGoingBack) {
setIsGoingBack(false);
}
},
[setOpenCancelConfirmation, blocker, isBlocking, setIsBlocking]
);

const handleCancelConfirmation = useCallback(() => {
if (isBlocking) {
blocker.proceed?.();
setIsBlocking(false);
} else if (isGoingBack) {
setIsGoingBack(false);
navigate(-1);
} else {
navigate(-1);
}
setOpenCancelConfirmation(false);
}, [navigate, setOpenCancelConfirmation]);
}, [
navigate,
setOpenCancelConfirmation,
blocker,
setIsBlocking,
isBlocking,
setIsGoingBack,
isGoingBack,
]);

const handleGoBack = useCallback(
(event: PopStateEvent) => {
event.preventDefault();
setIsGoingBack(true);
setOpenCancelConfirmation(true);
},
[setIsBlocking, setOpenCancelConfirmation]
);

useEffect(() => {
window.addEventListener("popstate", handleGoBack);
return () => {
window.removeEventListener("popstate", handleGoBack);
};
}, [handleGoBack]);

return {
openCancelConfirmation,
Expand Down

0 comments on commit 2710930

Please sign in to comment.