Skip to content

Instantly share code, notes, and snippets.

@nitaking
Last active May 25, 2022 10:41
Show Gist options
  • Save nitaking/088d654dcbcd4a186c45a7b7eccac16f to your computer and use it in GitHub Desktop.
Save nitaking/088d654dcbcd4a186c45a7b7eccac16f to your computer and use it in GitHub Desktop.
リロード時に離脱防止を防ぐ
import { useEffect } from 'react';
/**
* 一度入力した後にリロードすると、確認ダイアログを出す。
*/
export const useOnReloadAlert = () => {
useEffect(() => {
window.history.pushState(null, '', window.location.pathname);
const onReload = (event: BeforeUnloadEvent) => {
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', onReload);
return () => {
window.removeEventListener('beforeunload', onReload);
};
}, []);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment