diff --git a/src/hooks/useDiscardChangesConfirmation/index.native.ts b/src/hooks/useDiscardChangesConfirmation/index.native.ts index 4a14cb0b66a7..c90c7f9141c3 100644 --- a/src/hooks/useDiscardChangesConfirmation/index.native.ts +++ b/src/hooks/useDiscardChangesConfirmation/index.native.ts @@ -1,30 +1,30 @@ import type {NavigationAction} from '@react-navigation/native'; import {useIsFocused, usePreventRemove} from '@react-navigation/native'; -import {useCallback, useRef, useState} from 'react'; +import {useCallback, useEffect, useRef, useState} from 'react'; import {ModalActions} from '@components/Modal/Global/ModalContext'; import useConfirmModal from '@hooks/useConfirmModal'; import useLocalize from '@hooks/useLocalize'; import navigationRef from '@libs/Navigation/navigationRef'; import type UseDiscardChangesConfirmationOptions from './types'; -function useDiscardChangesConfirmation({getHasUnsavedChanges, onVisibilityChange, isEnabled = true}: UseDiscardChangesConfirmationOptions) { +function useDiscardChangesConfirmation({hasUnsavedChanges, onVisibilityChange, shouldNavigateAfterSave, navigateBack = () => {}}: UseDiscardChangesConfirmationOptions) { const {translate} = useLocalize(); const isFocused = useIsFocused(); const {showConfirmModal} = useConfirmModal(); const [shouldAllowNavigation, setShouldAllowNavigation] = useState(false); const blockedNavigationAction = useRef(undefined); - const shouldPrevent = isEnabled && isFocused && !shouldAllowNavigation; + useEffect(() => { + if (!shouldNavigateAfterSave) { + return; + } + navigateBack(); + }, [shouldNavigateAfterSave, navigateBack]); usePreventRemove( - shouldPrevent, + hasUnsavedChanges && isFocused && !shouldAllowNavigation, useCallback( ({data}: {data: {action: NavigationAction}}) => { - if (!getHasUnsavedChanges()) { - setShouldAllowNavigation(true); - navigationRef.current?.dispatch(data.action); - return; - } blockedNavigationAction.current = data.action; onVisibilityChange?.(true); showConfirmModal({ @@ -47,7 +47,7 @@ function useDiscardChangesConfirmation({getHasUnsavedChanges, onVisibilityChange } }); }, - [getHasUnsavedChanges, onVisibilityChange, showConfirmModal, translate], + [onVisibilityChange, showConfirmModal, translate], ), ); } diff --git a/src/hooks/useDiscardChangesConfirmation/index.ts b/src/hooks/useDiscardChangesConfirmation/index.ts index 5f0f7b035506..28252b5dbca0 100644 --- a/src/hooks/useDiscardChangesConfirmation/index.ts +++ b/src/hooks/useDiscardChangesConfirmation/index.ts @@ -1,8 +1,7 @@ import type {NavigationAction} from '@react-navigation/native'; -import {useIsFocused, useNavigation} from '@react-navigation/native'; -import {useCallback, useEffect, useRef} from 'react'; +import {useIsFocused, useNavigation, usePreventRemove} from '@react-navigation/native'; +import {useCallback, useEffect, useRef, useState} from 'react'; import {ModalActions} from '@components/Modal/Global/ModalContext'; -import useBeforeRemove from '@hooks/useBeforeRemove'; import useConfirmModal from '@hooks/useConfirmModal'; import useLocalize from '@hooks/useLocalize'; import setNavigationActionToMicrotaskQueue from '@libs/Navigation/helpers/setNavigationActionToMicrotaskQueue'; @@ -12,25 +11,27 @@ import type {PlatformStackNavigationProp} from '@libs/Navigation/PlatformStackNa import type {RootNavigatorParamList} from '@libs/Navigation/types'; import type UseDiscardChangesConfirmationOptions from './types'; -function useDiscardChangesConfirmation({getHasUnsavedChanges, onCancel, onVisibilityChange, isEnabled = true}: UseDiscardChangesConfirmationOptions) { +function useDiscardChangesConfirmation({hasUnsavedChanges, onCancel, onVisibilityChange, shouldNavigateAfterSave = false, navigateBack = () => {}}: UseDiscardChangesConfirmationOptions) { const navigation = useNavigation>(); - const isFocused = useIsFocused(); const {translate} = useLocalize(); const {showConfirmModal, closeModal} = useConfirmModal(); const blockedNavigationAction = useRef(undefined); - const shouldNavigateBack = useRef(false); + const [shouldNavigateBack, setShouldNavigateBack] = useState(false); const isDiscardModalOpenRef = useRef(false); + const isFocused = useIsFocused(); + const isConfirmed = useRef(false); + const [discardConfirmed, setDiscardConfirmed] = useState(false); - const navigateBack = useCallback(() => { + const goBack = useCallback(() => { if (blockedNavigationAction.current) { navigationRef.current?.dispatch(blockedNavigationAction.current); return; } - if (!shouldNavigateBack.current) { + if (!shouldNavigateBack) { return; } navigationRef.current?.goBack(); - }, []); + }, [shouldNavigateBack]); const showDiscardModal = useCallback(() => { onVisibilityChange?.(true); @@ -42,50 +43,57 @@ function useDiscardChangesConfirmation({getHasUnsavedChanges, onCancel, onVisibi confirmText: translate('discardChangesConfirmation.confirmText'), cancelText: translate('common.cancel'), shouldIgnoreBackHandlerDuringTransition: true, + onModalHide: () => { + if (isConfirmed.current) { + setNavigationActionToMicrotaskQueue(goBack); + } else { + setShouldNavigateBack(false); + onCancel?.(); + } + }, }).then((result) => { isDiscardModalOpenRef.current = false; onVisibilityChange?.(false); if (result.action === ModalActions.CONFIRM) { - setNavigationActionToMicrotaskQueue(navigateBack); + setDiscardConfirmed(true); + setNavigationActionToMicrotaskQueue(goBack); } else { blockedNavigationAction.current = undefined; - shouldNavigateBack.current = false; + setShouldNavigateBack(false); onCancel?.(); } }); - }, [showConfirmModal, translate, navigateBack, onCancel, onVisibilityChange]); + }, [showConfirmModal, translate, goBack, onCancel, onVisibilityChange]); - useBeforeRemove( + usePreventRemove( + (hasUnsavedChanges && !discardConfirmed) || shouldNavigateBack, useCallback( (e) => { - if (!isEnabled || !isFocused || !getHasUnsavedChanges() || shouldNavigateBack.current) { - return; - } - - e.preventDefault(); blockedNavigationAction.current = e.data.action; navigateAfterInteraction(showDiscardModal); }, - [getHasUnsavedChanges, isFocused, isEnabled, showDiscardModal], + [showDiscardModal], ), - isEnabled && isFocused, ); + useEffect(() => { + if (!shouldNavigateAfterSave) { + return; + } + navigateBack(); + }, [shouldNavigateAfterSave, navigateBack]); + /** * We cannot programmatically stop the browser's back navigation like react-navigation's beforeRemove. * Events like popstate and transitionStart are triggered AFTER the back navigation has already completed. * So we need to go forward to get back to the current page. */ useEffect(() => { - if (!isEnabled || !isFocused) { - return undefined; - } const unsubscribe = navigation.addListener('transitionStart', ({data: {closing}}) => { - // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing - if (!getHasUnsavedChanges()) { + if (!hasUnsavedChanges || isConfirmed.current) { return; } - shouldNavigateBack.current = true; + setShouldNavigateBack(true); if (closing) { window.history.go(1); return; @@ -95,20 +103,20 @@ function useDiscardChangesConfirmation({getHasUnsavedChanges, onCancel, onVisibi }); return unsubscribe; - }, [navigation, getHasUnsavedChanges, isFocused, isEnabled, showDiscardModal]); + }, [hasUnsavedChanges, navigation, showDiscardModal]); /** - * When the screen loses focus (or is disabled) while the discard modal is open, + * When the screen loses focus while the discard modal is open, * close the modal and reset refs so we don't leave the modal visible or stale state. */ useEffect(() => { - if ((isFocused && isEnabled) || !isDiscardModalOpenRef.current) { + if (isFocused) { return; } closeModal(); blockedNavigationAction.current = undefined; - shouldNavigateBack.current = false; - }, [isFocused, isEnabled, closeModal]); + setShouldNavigateBack(false); + }, [isFocused, closeModal]); } export default useDiscardChangesConfirmation; diff --git a/src/hooks/useDiscardChangesConfirmation/types.ts b/src/hooks/useDiscardChangesConfirmation/types.ts index 6ce984e471f4..abe98e977bf1 100644 --- a/src/hooks/useDiscardChangesConfirmation/types.ts +++ b/src/hooks/useDiscardChangesConfirmation/types.ts @@ -1,8 +1,10 @@ type UseDiscardChangesConfirmationOptions = { - getHasUnsavedChanges: () => boolean; - onCancel?: () => void; - onVisibilityChange?: (visible: boolean) => void; isEnabled?: boolean; + hasUnsavedChanges: boolean; + onVisibilityChange?: (visible: boolean) => void; + onCancel?: () => void; + shouldNavigateAfterSave?: boolean; + navigateBack?: () => void; }; export default UseDiscardChangesConfirmationOptions; diff --git a/src/pages/iou/request/step/DiscardChangesConfirmation/index.native.tsx b/src/pages/iou/request/step/DiscardChangesConfirmation/index.native.tsx new file mode 100644 index 000000000000..9e9298e78952 --- /dev/null +++ b/src/pages/iou/request/step/DiscardChangesConfirmation/index.native.tsx @@ -0,0 +1,57 @@ +import {usePreventRemove} from '@react-navigation/native'; +import type {NavigationAction} from '@react-navigation/native'; +import React, {memo, useCallback, useRef, useState} from 'react'; +import ConfirmModal from '@components/ConfirmModal'; +import useLocalize from '@hooks/useLocalize'; +import navigationRef from '@libs/Navigation/navigationRef'; +import type DiscardChangesConfirmationProps from './types'; + +function DiscardChangesConfirmation({hasUnsavedChanges, onVisibilityChange}: DiscardChangesConfirmationProps) { + const {translate} = useLocalize(); + const [isVisible, setIsVisible] = useState(false); + const blockedNavigationAction = useRef(undefined); + + usePreventRemove( + hasUnsavedChanges, + useCallback((e) => { + blockedNavigationAction.current = e.data.action; + setIsVisible(true); + }, []), + ); + + const setModalVisible = useCallback( + (nextVisible: boolean) => { + setIsVisible(nextVisible); + onVisibilityChange?.(nextVisible); + }, + [onVisibilityChange], + ); + + return ( + { + setIsVisible(false); + setModalVisible(false); + if (blockedNavigationAction.current) { + navigationRef.current?.dispatch(blockedNavigationAction.current); + blockedNavigationAction.current = undefined; + } else { + navigationRef.current?.goBack(); + } + }} + onCancel={() => { + setModalVisible(false); + blockedNavigationAction.current = undefined; + }} + shouldHandleNavigationBack + /> + ); +} + +export default memo(DiscardChangesConfirmation); diff --git a/src/pages/iou/request/step/DiscardChangesConfirmation/types.ts b/src/pages/iou/request/step/DiscardChangesConfirmation/types.ts new file mode 100644 index 000000000000..e504568466a4 --- /dev/null +++ b/src/pages/iou/request/step/DiscardChangesConfirmation/types.ts @@ -0,0 +1,10 @@ +type DiscardChangesConfirmationProps = { + onCancel?: () => void; + hasUnsavedChanges: boolean; + shouldNavigateAfterSave?: boolean; + navigateBack?: () => void; + /** Notifies when the discard modal visibility changes */ + onVisibilityChange?: (isVisible: boolean) => void; +}; + +export default DiscardChangesConfirmationProps; diff --git a/src/pages/iou/request/step/IOURequestStepDescription.tsx b/src/pages/iou/request/step/IOURequestStepDescription.tsx index 38c742d0a65b..0910ebcf69bf 100644 --- a/src/pages/iou/request/step/IOURequestStepDescription.tsx +++ b/src/pages/iou/request/step/IOURequestStepDescription.tsx @@ -1,5 +1,5 @@ import lodashIsEmpty from 'lodash/isEmpty'; -import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'; +import React, {useCallback, useMemo, useState} from 'react'; import {InteractionManager, View} from 'react-native'; import type {OnyxEntry} from 'react-native-onyx'; import FormProvider from '@components/Form/FormProvider'; @@ -73,10 +73,8 @@ function IOURequestStepDescription({ return isEditingSplit && !lodashIsEmpty(splitDraftTransaction) ? (splitDraftTransaction?.comment?.comment ?? '') : (transaction?.comment?.comment ?? ''); }, [isTransactionDraft, iouType, isEditingSplit, splitDraftTransaction, transaction?.comment?.comment]); - const [currentDescription, setCurrentDescription] = useState(currentDescriptionInMarkdown); - const [isSaved, setIsSaved] = useState(false); + const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false); const [isDiscardModalVisible, setIsDiscardModalVisible] = useState(false); - const shouldNavigateAfterSaveRef = useRef(false); useRestartOnReceiptFailure(transaction, reportID, iouType, action); const currentUserPersonalDetails = useCurrentUserPersonalDetails(); const currentUserAccountIDParam = currentUserPersonalDetails.accountID; @@ -122,35 +120,35 @@ function IOURequestStepDescription({ Navigation.goBack(backTo); }, [backTo]); - useEffect(() => { - if (!isSaved || !shouldNavigateAfterSaveRef.current) { - return; - } - shouldNavigateAfterSaveRef.current = false; - navigateBack(); - }, [isSaved, navigateBack]); + const [shouldNavigateAfterSave, setShouldNavigateAfterSave] = useState(false); - const updateDescriptionRef = (value: string) => { - setCurrentDescription(value); - }; + const updateHasUnsavedChanges = useCallback( + (value: string) => { + if (value === currentDescriptionInMarkdown) { + setHasUnsavedChanges(false); + return; + } + setHasUnsavedChanges(true); + }, + [currentDescriptionInMarkdown], + ); const updateComment = (value: FormOnyxValues) => { if (!transaction?.transactionID) { return; } + setHasUnsavedChanges(false); const newComment = value.moneyRequestComment.trim(); if (newComment === currentDescriptionInMarkdown) { - setIsSaved(true); - shouldNavigateAfterSaveRef.current = true; + setShouldNavigateAfterSave(true); return; } if (isEditingSplit) { setDraftSplitTransaction(transaction?.transactionID, splitDraftTransaction, {comment: newComment}); - setIsSaved(true); - shouldNavigateAfterSaveRef.current = true; + setShouldNavigateAfterSave(true); return; } @@ -171,9 +169,7 @@ function IOURequestStepDescription({ parentReportNextStep, }); } - - setIsSaved(true); - shouldNavigateAfterSaveRef.current = true; + setShouldNavigateAfterSave(true); }; // eslint-disable-next-line rulesdir/no-negated-variables @@ -191,13 +187,10 @@ function IOURequestStepDescription({ inputRef.current?.focus(); }); }, - getHasUnsavedChanges: () => { - if (isSaved) { - return false; - } - return currentDescription !== currentDescriptionInMarkdown; - }, + hasUnsavedChanges, onVisibilityChange: setIsDiscardModalVisible, + shouldNavigateAfterSave, + navigateBack, }); return ( @@ -224,7 +217,7 @@ function IOURequestStepDescription({ inputID={INPUT_IDS.MONEY_REQUEST_COMMENT} name={INPUT_IDS.MONEY_REQUEST_COMMENT} defaultValue={currentDescriptionInMarkdown} - onValueChange={updateDescriptionRef} + onValueChange={updateHasUnsavedChanges} label={translate('moneyRequestConfirmationList.whatsItFor')} accessibilityLabel={translate('moneyRequestConfirmationList.whatsItFor')} role={CONST.ROLE.PRESENTATION} diff --git a/src/pages/iou/request/step/IOURequestStepDistanceOdometer.tsx b/src/pages/iou/request/step/IOURequestStepDistanceOdometer.tsx index 421d7a07cf12..432c46d4d8e1 100644 --- a/src/pages/iou/request/step/IOURequestStepDistanceOdometer.tsx +++ b/src/pages/iou/request/step/IOURequestStepDistanceOdometer.tsx @@ -86,16 +86,14 @@ function IOURequestStepDistanceOdometer({ // Key to force TextInput remount when resetting state after tab switch const [inputKey, setInputKey] = useState(0); - // Track initial values for DiscardChangesConfirmation - const initialStartReadingRef = useRef(''); - const initialEndReadingRef = useRef(''); + // Baseline readings for DiscardChangesConfirmation + const [initialReadings, setInitialReadings] = useState<{start: string; end: string}>({start: '', end: ''}); + const [odometerImage, setOdometerImage] = useState<{start?: FileObject | string; end?: FileObject | string}>({}); const hasInitializedRefs = useRef(false); // Track local state via refs to avoid including them in useEffect dependencies - const startReadingRef = useRef(''); - const endReadingRef = useRef(''); - const initialStartImageRef = useRef(undefined); - const initialEndImageRef = useRef(undefined); const prevSelectedTabRef = useRef(undefined); + // Compute local state presence + const hasLocalState = useMemo(() => !!startReading || !!endReading, [startReading, endReading]); const [reportNameValuePairs] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report?.reportID}`); const isArchived = isArchivedReport(reportNameValuePairs); @@ -164,12 +162,8 @@ function IOURequestStepDistanceOdometer({ if (prevSelectedTab === CONST.TAB_REQUEST.DISTANCE_ODOMETER && selectedTab !== CONST.TAB_REQUEST.DISTANCE_ODOMETER) { setStartReading(''); setEndReading(''); - startReadingRef.current = ''; - endReadingRef.current = ''; - initialStartReadingRef.current = ''; - initialEndReadingRef.current = ''; - initialStartImageRef.current = undefined; - initialEndImageRef.current = undefined; + setInitialReadings({start: '', end: ''}); + setOdometerImage({start: undefined, end: undefined}); setFormError(''); // Force TextInput remount to reset label position setInputKey((prev) => prev + 1); @@ -188,10 +182,8 @@ function IOURequestStepDistanceOdometer({ const currentEnd = currentTransaction?.comment?.odometerEnd; const startValue = currentStart !== null && currentStart !== undefined ? currentStart.toString() : ''; const endValue = currentEnd !== null && currentEnd !== undefined ? currentEnd.toString() : ''; - initialStartReadingRef.current = startValue; - initialEndReadingRef.current = endValue; - initialStartImageRef.current = currentTransaction?.comment?.odometerStartImage; - initialEndImageRef.current = currentTransaction?.comment?.odometerEndImage; + setInitialReadings({start: startValue, end: endValue}); + setOdometerImage({start: currentTransaction?.comment?.odometerStartImage, end: currentTransaction?.comment?.odometerEndImage}); hasInitializedRefs.current = true; }, [ currentTransaction?.comment?.odometerStart, @@ -211,7 +203,6 @@ function IOURequestStepDistanceOdometer({ // 2. We're editing and transaction has data (to load existing values), OR // 3. Transaction has data but local state is empty (user navigated back from another page) const hasTransactionData = (currentStart !== null && currentStart !== undefined) || (currentEnd !== null && currentEnd !== undefined); - const hasLocalState = startReadingRef.current || endReadingRef.current; const shouldInitialize = (!hasInitializedRefs.current && hasTransactionData) || (isEditing && hasTransactionData && !hasLocalState) || @@ -224,11 +215,9 @@ function IOURequestStepDistanceOdometer({ if (startValue || endValue) { setStartReading(startValue); setEndReading(endValue); - startReadingRef.current = startValue; - endReadingRef.current = endValue; } } - }, [currentTransaction?.comment?.odometerStart, currentTransaction?.comment?.odometerEnd, isEditing]); + }, [currentTransaction?.comment?.odometerStart, currentTransaction?.comment?.odometerEnd, isEditing, hasLocalState]); // Calculate total distance - updated live after every input change const totalDistance = (() => { @@ -309,7 +298,6 @@ function IOURequestStepDistanceOdometer({ return; } setStartReading(text); - startReadingRef.current = text; if (formError) { setFormError(''); } @@ -320,7 +308,6 @@ function IOURequestStepDistanceOdometer({ return; } setEndReading(text); - endReadingRef.current = text; if (formError) { setFormError(''); } @@ -450,9 +437,7 @@ function IOURequestStepDistanceOdometer({ return; } - if (shouldSkipConfirmation) { - setShouldEnableDiscardConfirmation(false); - } + setShouldEnableDiscardConfirmation(false); handleMoneyRequestStepDistanceNavigation({ iouType, @@ -542,13 +527,15 @@ function IOURequestStepDistanceOdometer({ .finally(() => setIsSubmitting(false)); }; + const hasUnsavedChanges = useMemo( + () => + shouldEnableDiscardConfirmation && + (startReading !== initialReadings.start || endReading !== initialReadings.end || odometerImage.start !== odometerStartImage || odometerImage.end !== odometerEndImage), + [shouldEnableDiscardConfirmation, startReading, endReading, initialReadings.start, initialReadings.end, odometerImage.start, odometerImage.end, odometerStartImage, odometerEndImage], + ); + useDiscardChangesConfirmation({ - isEnabled: shouldEnableDiscardConfirmation, - getHasUnsavedChanges: () => { - const hasReadingChanges = startReadingRef.current !== initialStartReadingRef.current || endReadingRef.current !== initialEndReadingRef.current; - const hasImageChanges = transaction?.comment?.odometerStartImage !== initialStartImageRef.current || transaction?.comment?.odometerEndImage !== initialEndImageRef.current; - return hasReadingChanges || hasImageChanges; - }, + hasUnsavedChanges, }); return ( diff --git a/src/pages/iou/request/step/IOURequestStepMerchant.tsx b/src/pages/iou/request/step/IOURequestStepMerchant.tsx index 53ed15bcd41f..df446500b967 100644 --- a/src/pages/iou/request/step/IOURequestStepMerchant.tsx +++ b/src/pages/iou/request/step/IOURequestStepMerchant.tsx @@ -1,4 +1,4 @@ -import React, {useCallback, useEffect, useRef, useState} from 'react'; +import React, {useCallback, useState} from 'react'; import {InteractionManager, View} from 'react-native'; import FormProvider from '@components/Form/FormProvider'; import InputWrapper from '@components/Form/InputWrapper'; @@ -60,15 +60,24 @@ function IOURequestStepMerchant({ const merchant = getTransactionDetails(isEditingSplitBill && !isEmptyObject(splitDraftTransaction) ? splitDraftTransaction : transaction)?.merchant; const isEmptyMerchant = isInvalidMerchantValue(merchant); const initialMerchant = isEmptyMerchant ? '' : merchant; - const [currentMerchant, setCurrentMerchant] = useState(initialMerchant); - const [isSaved, setIsSaved] = useState(false); const [isDiscardModalVisible, setIsDiscardModalVisible] = useState(false); - const shouldNavigateAfterSaveRef = useRef(false); const currentUserPersonalDetails = useCurrentUserPersonalDetails(); const currentUserAccountIDParam = currentUserPersonalDetails.accountID; const currentUserEmailParam = currentUserPersonalDetails.login ?? ''; const {isBetaEnabled} = usePermissions(); const isASAPSubmitBetaEnabled = isBetaEnabled(CONST.BETAS.ASAP_SUBMIT); + const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false); + + const updateHasUnsavedChanges = useCallback( + (value: string) => { + if (value === initialMerchant) { + setHasUnsavedChanges(false); + return; + } + setHasUnsavedChanges(true); + }, + [initialMerchant], + ); const isMerchantRequired = isPolicyExpenseChat(report) || isExpenseRequest(report) || transaction?.participants?.some((participant) => !!participant.isPolicyExpenseChat); @@ -76,14 +85,6 @@ function IOURequestStepMerchant({ Navigation.goBack(backTo); }, [backTo]); - useEffect(() => { - if (!isSaved || !shouldNavigateAfterSaveRef.current) { - return; - } - shouldNavigateAfterSaveRef.current = false; - navigateBack(); - }, [isSaved, navigateBack]); - const validate = useCallback( (value: FormOnyxValues) => { const errors: FormInputErrors = {}; @@ -103,23 +104,20 @@ function IOURequestStepMerchant({ [isMerchantRequired, translate], ); - const updateMerchantRef = (value: string) => { - setCurrentMerchant(value); - }; + const [shouldNavigateAfterSave, setShouldNavigateAfterSave] = useState(false); const updateMerchant = (value: FormOnyxValues) => { + setHasUnsavedChanges(false); const newMerchant = value.moneyRequestMerchant?.trim(); if (isEditingSplitBill) { setDraftSplitTransaction(transactionID, splitDraftTransaction, {merchant: newMerchant}); - setIsSaved(true); - shouldNavigateAfterSaveRef.current = true; + setShouldNavigateAfterSave(true); return; } if (newMerchant === merchant || (newMerchant === '' && merchant === CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT)) { - setIsSaved(true); - shouldNavigateAfterSaveRef.current = true; + setShouldNavigateAfterSave(true); return; } setMoneyRequestMerchant(transactionID, newMerchant || CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT, !isEditing); @@ -138,8 +136,7 @@ function IOURequestStepMerchant({ parentReportNextStep, }); } - setIsSaved(true); - shouldNavigateAfterSaveRef.current = true; + setShouldNavigateAfterSave(true); }; useDiscardChangesConfirmation({ @@ -149,12 +146,9 @@ function IOURequestStepMerchant({ inputRef.current?.focus(); }); }, - getHasUnsavedChanges: () => { - if (isSaved) { - return false; - } - return currentMerchant !== initialMerchant; - }, + hasUnsavedChanges, + shouldNavigateAfterSave, + navigateBack, onVisibilityChange: setIsDiscardModalVisible, }); @@ -183,7 +177,7 @@ function IOURequestStepMerchant({ inputID={INPUT_IDS.MONEY_REQUEST_MERCHANT} name={INPUT_IDS.MONEY_REQUEST_MERCHANT} defaultValue={initialMerchant} - onValueChange={updateMerchantRef} + onValueChange={updateHasUnsavedChanges} label={translate('common.merchant')} accessibilityLabel={translate('common.merchant')} role={CONST.ROLE.PRESENTATION} diff --git a/src/pages/settings/Profile/Avatar/AvatarPage.tsx b/src/pages/settings/Profile/Avatar/AvatarPage.tsx index a70db9848cbd..7f7e01f0f734 100644 --- a/src/pages/settings/Profile/Avatar/AvatarPage.tsx +++ b/src/pages/settings/Profile/Avatar/AvatarPage.tsx @@ -51,7 +51,7 @@ function ProfileAvatar() { const [selected, setSelected] = useState(); const avatarCaptureRef = useRef(null); - const isSavingRef = useRef(false); + const [isSaving, setIsSaving] = useState(false); const icons = useMemoizedLazyExpensifyIcons(['Upload']); const styles = useThemeStyles(); @@ -62,7 +62,7 @@ function ProfileAvatar() { const isDirty = imageData.uri !== '' || !!selected; useDiscardChangesConfirmation({ - getHasUnsavedChanges: () => !isSavingRef.current && isDirty, + hasUnsavedChanges: !isSaving && isDirty, }); const avatarStyle = [styles.avatarXLarge, styles.alignSelfStart, styles.alignSelfCenter]; @@ -153,7 +153,7 @@ function ProfileAvatar() { }); const onPress = useCallback(() => { - isSavingRef.current = true; + setIsSaving(true); if (imageData.file) { updateAvatar(imageData.file, { @@ -184,7 +184,7 @@ function ProfileAvatar() { return; } if (!selected || !avatarCaptureRef.current) { - isSavingRef.current = false; + setIsSaving(false); return; } // User selected a letter avatar @@ -201,7 +201,7 @@ function ProfileAvatar() { Navigation.dismissModal(); }) .catch(() => { - isSavingRef.current = false; + setIsSaving(false); }); }, [currentUserPersonalDetails?.accountID, currentUserPersonalDetails?.avatar, currentUserPersonalDetails?.avatarThumbnail, imageData.file, selected]);