add control to prevent unsaved changes

in profile edit if user tries to navigate away from the site
show native confirmation message asking user's consent
This commit is contained in:
Nuwan 2024-08-19 19:53:04 +05:30
parent 5a00f45d5c
commit e973a5f55c
1 changed files with 11 additions and 15 deletions

View File

@ -5,7 +5,7 @@ import FalconCardHeader from '../common/FalconCardHeader';
import { useTranslation } from 'react-i18next';
import JKProfileAvatar from '../profile/JKProfileAvatar';
import { useAuth } from '../../context/UserAuth';
import { useForm, Controller, set } from 'react-hook-form';
import { useForm, Controller } from 'react-hook-form';
import {
getPersonById,
getInstruments,
@ -45,7 +45,7 @@ function JKEditProfile() {
{ value: '3', label: t('profeciency.advanced') }
];
const { register, control, handleSubmit, setValue, getValues } = useForm({
const { register, control, handleSubmit, setValue, getValues, isDirty } = useForm({
defaultValues: {
firstName: '',
lastName: '',
@ -396,20 +396,16 @@ function JKEditProfile() {
};
useEffect(() => {
const handleBeforeUnload = event => {
// Perform actions before the component unloads
if (!updating) {
alert('Please let the page finish updating before leaving');
return;
}
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', handleBeforeUnload);
function beforeUnload(e) {
if (updating) e.preventDefault();
}
window.addEventListener('beforeunload', beforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
window.removeEventListener('beforeunload', beforeUnload);
};
}, []);
}, [updating]);
const toggleAvatarUpload = () => {
setShowAvatarUpload(!showAvatarUpload);
@ -417,7 +413,7 @@ function JKEditProfile() {
return (
<>
<Prompt when={updating} message="The changes are been saved. Are you sure you want to leave?" />
<Prompt when={updating} message="The changes are being saved. Are you sure you want to leave?" />
<Card>
<FalconCardHeader title={t('page_title', { ns: 'profile' })} titleClass="font-weight-bold">
{updating && (