Created
February 6, 2022 21:44
-
-
Save geovanisouza92/5c0d060dc4030a47ec1c63920a34db5b to your computer and use it in GitHub Desktop.
Ask user confirmation before exit page when react-hook-form is dirty
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
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