Skip to content

Instantly share code, notes, and snippets.

@serifcolakel
Forked from MarksCode/use-prompt.ts
Created June 6, 2023 20:40
Show Gist options
  • Save serifcolakel/b13ff7f0b946ef8c4abdda72f177faee to your computer and use it in GitHub Desktop.
Save serifcolakel/b13ff7f0b946ef8c4abdda72f177faee to your computer and use it in GitHub Desktop.
return `usePrompt` capabilities from react-router
/**
* Prompts a user when they exit the page
*/
import { useCallback, useContext, useEffect } from 'react';
import { UNSAFE_NavigationContext as NavigationContext } from 'react-router-dom';
function useConfirmExit(confirmExit: () => boolean, when = true) {
const { navigator } = useContext(NavigationContext);
useEffect(() => {
if (!when) {
return;
}
const push = navigator.push;
navigator.push = (...args: Parameters<typeof push>) => {
const result = confirmExit();
if (result !== false) {
push(...args);
}
};
return () => {
navigator.push = push;
};
}, [navigator, confirmExit, when]);
}
export function usePrompt(message: string, when = true) {
useEffect(() => {
if (when) {
window.onbeforeunload = function () {
return message;
};
}
return () => {
window.onbeforeunload = null;
};
}, [message, when]);
const confirmExit = useCallback(() => {
const confirm = window.confirm(message);
return confirm;
}, [message]);
useConfirmExit(confirmExit, when);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment