history#Blocker TypeScript Examples
The following examples show how to use
history#Blocker.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: router.ts From mui-toolpad with MIT License | 6 votes |
/**
* @source https://github.com/remix-run/react-router/commit/256cad70d3fd4500b1abcfea66f3ee622fb90874
*/
export function useBlocker(blocker: Blocker, when = true) {
const { navigator } = React.useContext(NavigationContext) as NavigationContextWithBlock;
const refUnBlock = React.useRef<() => void>();
const blockerRef = React.useRef(blocker);
React.useEffect(() => {
blockerRef.current = blocker;
}, [blocker]);
React.useEffect(() => {
if (!when) {
refUnBlock.current?.();
refUnBlock.current = undefined;
return;
}
if (!refUnBlock.current) {
refUnBlock.current = navigator.block((tx: Transition) => {
const autoUnblockingTx = {
...tx,
retry() {
refUnBlock.current?.(); // need to unblock so retry succeeds
tx.retry();
},
};
blockerRef.current(autoUnblockingTx);
});
}
}, [navigator, when]);
}
Example #2
Source File: useUnsavedChangesDialog.tsx From firecms with MIT License | 5 votes |
export function useNavigationUnsavedChangesDialog(when: boolean, onSuccess: () => void):
{
navigationWasBlocked: boolean,
handleCancel: () => void,
handleOk: () => void
} {
const [nextLocation, setNextLocation] = React.useState<any | undefined>();
const { navigator } = React.useContext(UNSAFE_NavigationContext);
const navigate = useNavigate();
const handleCancel = () => {
setNextLocation(undefined);
};
const handleOk = () => {
onSuccess();
setNextLocation(undefined);
navigate(-1);
};
const blocker: Blocker = useCallback(({ action, location: nextLocation, retry }) => {
switch (action) {
case "REPLACE": {
retry();
return;
}
case "POP": {
setNextLocation(nextLocation);
}
}
}, []);
React.useEffect(() => {
if (!when) return;
if (nextLocation) return;
if (!("block" in navigator)) return;
const unblock = (navigator as any).block((tx: Transition) => {
const autoUnblockingTx = {
...tx,
retry() {
unblock();
tx.retry();
}
};
blocker(autoUnblockingTx);
});
return unblock;
}, [navigator, blocker, when, nextLocation]);
return { navigationWasBlocked: Boolean(nextLocation), handleCancel, handleOk };
}