Files
bodyshop/client/src/utils/prompt.js
Dave Richer 16d040daf9 Fix prompt, and modal.
Signed-off-by: Dave Richer <dave@imexsystems.ca>
2023-12-12 15:18:51 -05:00

46 lines
1.3 KiB
JavaScript

import {useBeforeUnload, useBlocker} from "react-router-dom";
import {useCallback, useEffect, useRef} from "react";
function usePrompt(message, {beforeUnload} = {}) {
let blocker = useBlocker(
useCallback(
(location) => {
// This has been put in, so it does not affect transitions between the same page
if (location.currentLocation.pathname === location.nextLocation.pathname) {
return false;
}
return typeof message === "string" ? !window.confirm(message) : false;
},
[message]
)
);
let prevState = useRef(blocker.state);
useEffect(() => {
if (blocker.state === "blocked") {
blocker.reset();
}
prevState.current = blocker.state;
}, [blocker]);
useBeforeUnload(
useCallback(
(event) => {
if (beforeUnload && typeof message === "string") {
event.preventDefault();
event.returnValue = message;
}
},
[message, beforeUnload]
),
{capture: true}
);
}
function Prompt({when, message, ...props}) {
usePrompt(when ? message : false, props);
return null;
}
export default Prompt;