Skip to content

Instantly share code, notes, and snippets.

@RyotaBannai
Forked from sibelius/usePrompt.tsx
Created August 2, 2020 13:26
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Prompt user before leaving route or reload
import { useEffect, useRef } from 'react';
import { useHistory } from 'react-router-dom';
export const usePrompt = (when: boolean, message: string = 'Are you sure you want to quit without saving your changes?') => {
const history = useHistory();
const self = useRef(null);
const onWindowOrTabClose = event => {
if (!when) {
return;
}
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
};
useEffect(() => {
if (when) {
self.current = history.block(message);
} else {
self.current = null;
}
window.addEventListener('beforeunload', onWindowOrTabClose);
return () => {
if (self.current) {
self.current();
self.current = null;
}
window.removeEventListener('beforeunload', onWindowOrTabClose);
}
}, [message, when]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment