Last active
May 25, 2022 10:41
-
-
Save nitaking/088d654dcbcd4a186c45a7b7eccac16f to your computer and use it in GitHub Desktop.
リロード時に離脱防止を防ぐ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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