Skip to content

Instantly share code, notes, and snippets.

@geovanisouza92
Created February 6, 2022 21:44
Show Gist options
  • Save geovanisouza92/5c0d060dc4030a47ec1c63920a34db5b to your computer and use it in GitHub Desktop.
Save geovanisouza92/5c0d060dc4030a47ec1c63920a34db5b to your computer and use it in GitHub Desktop.
Ask user confirmation before exit page when react-hook-form is dirty
export function LoginForm() {
const { register, handleSubmit, formState: { isDirty } } = useForm();
useBeforeUnload((event) => {
if (isDirty) event.preventDefault();
});
const login = (data) => console.log(data);
return (
<form onSubmit={handleSubmit(login)}>
<label>
Email:
<input {...register('email')} />
</label>
<label>
Password:
<input {...register('password')} />
</label>
<button type="submit">Submit</button>
</form>
);
}
function useBeforeUnload(/** @type {(event: Event) => void} */ handler) {
/** @type {import('react').Ref<(event: Event) => void>} */
const handlerRef = useRef();
useEffect(() => {
handlerRef.current = (/** @type {Event} */ event) => {
const returnValue = handler?.(event);
if (typeof returnValue === 'string') {
return (event.returnValue = returnValue);
}
if (event.defaultPrevented) {
return (event.returnValue = '');
}
};
}, [handler]);
useEffect(() => {
const listener = (/** @type {Event} */ event) => handlerRef.current?.(event);
window.addEventListener('beforeunload', listener);
return () => window.removeEventListener('beforeunload', listener);
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment