[Due for payment 2026-11-25] [$250] Issue with adding contact method in offline mode
If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.
Version Number: 9.5.14-1 Reproducible in staging?: yes Reproducible in production?: yes If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://test-management.browserstack.com/projects/2219752/test-plans/203241/linked-test-cases/79083052/41236653/1869288445?p=1&q=TC-3301
Action Performed:
- Navigate to account settings > Profile
- Click on "Contact Method"
- Verify the main contact method is the user email
- Click on "New Contact method"
- Verify the user is requested to add the magic code sent to the main account
- Navigate to the email inbox
- Verify the email you receive reads ".....trying to: • Add a new contact method to your account"
- Verify no sign-in button is rendered
- Enter the magic code sent to the main account and Click "Verify"
- Add a email you have access to
- Verify you're now requested to enter the magic code sent to the secondary contact
- Do not validate the secondary login yet - Click on back arrow to navigate back to profile page
- Verify the email is added as contact method with GBR
- Click on the contact method push row
- Verify enter the magic code page displayed
- Copy the Magic Code included in the validation email
- Verify the email you receive has the subject "Verify secondary email for Expensify" and looks different from all the other magic code emails
- Disable the internet connection
- Verify the "Verify" button is disabled
- Paste the magic code found in the email inbox in the field
- Verify the user is not redirected back to the contact methods list
- Enable the internet connection in the device
Expected Result:
User should be navigated back to the contact methods list
Actual Result:
User is getting navigated to the contact method details screen
Workaround:
Can the user still use Expensify without this being fixed? Have you informed them of the workaround?
Platforms:
Select the officially supported platforms where the issue was reproduced:
- [x] Android: App
- [ ] Android: mWeb Chrome
- [ ] iOS: App
- [ ] iOS: mWeb Safari
- [ ] iOS: mWeb Chrome
- [ ] Windows: Chrome
- [ ] MacOS: Chrome / Safari
Screenshots/Videos
https://github.com/user-attachments/assets/30803b83-a4b9-43d8-bda5-90bca3949d0a
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022112501287831531014
- Upwork Job ID: 2112501287831531014
- Last Price Increase: 2026-11-02
Issue Owner
Current Issue Owner: @mallenexpensify
⚠️ Preliminary analysis (low confidence) — treat as a starting point, not a conclusion.
I think the "go back to the list" call is skipped, or does nothing, when validation finishes after reconnecting on Android. The page then stays open and switches to the validated details view, which matches the actual result.
The only trigger for going back is a one-time effect in DynamicContactMethodDetailsPage.tsx:133-161. It fires once, when validatedDate goes from empty to set, and calls Navigation.goBack(listPath). I see two weak points:
- The target is computed from global state.
listPathcomes from useDynamicBackPath.ts:24-44. That hook reads whichever route is focused in the whole navigation tree, not this screen's route. After a reconnect,validatedDatelands in the same batch as theReconnectAppdata. If the focused path is different at that moment,goBackgoes to the wrong route or does nothing. 83362 migrate settings profile part 2 v2 replaced the old static route with this hook. - Nothing retries. If
goBackbails out, it only logsLog.hmmmand the effect never fires again.
While offline, the code is never sent. ValidateCodeInput.tsx:237-253 blocks submit and submits automatically on reconnect. So this flow differs from the online flow only in timing: validation completes right after the reconnect.
Related: [Due for payment 2026-03-17] Contact method - After going online, user not redirected to contact method list on verifying secondary login (closed) had the same symptom. fix: prevent navigation logic when screen isn't focused fixed it for the case where the troubleshoot modal had focus. This report is an Android variant that fix doesn't cover.
Possible fix: Go back whenever the page saw the login unvalidated and it is now validated and the screen is focused. Re-check when focus changes. Build the list path from this screen's own route, not from global navigation state.
I couldn't verify this. The bug is Android-only, and reproducing it needs the magic code sent to the secondary email. To confirm it, reproduce on Android and check for two things:
- Client logs around the
ValidateSecondaryLoginresponse contain[Navigation] Unable to go up. - What
listPathis when the effect fires.
Next Steps: Reply with @MelvinBot <your feedback> to refine this analysis.
Triggered auto assignment to Contributor-plus team member for initial proposal review - @getusha (External)
Job added to Upwork: https://www.upwork.com/jobs/~022112501287831531014
Proposal
Please re-state the problem that we are trying to solve in this issue.
When adding a secondary contact method while offline and submitting the magic code, once the device reconnects to the internet and validation succeeds, the user is not navigated back to the contact methods list and remains on the contact method details screen (which transitions into its validated state).
What is the root cause of that problem?
In src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx:133-161:
- The screen relies on an effect watching
validatedDateto trigger navigation back to the list:const prevValidatedDate = usePrevious(loginData?.validatedDate); const isFocused = useIsFocused(); const [shouldNavigateOnFocus, setShouldNavigateOnFocus] = useState(false); useEffect(() => { if (prevValidatedDate || !loginData?.validatedDate) { return; } if (isFocused) { Navigation.goBack(listPath); } else { setShouldNavigateOnFocus(true); } }, [prevValidatedDate, loginData?.validatedDate, isDefaultContactMethod, listPath]); - When submitting while offline,
validateSecondaryLoginplaces the network request in Onyx's sequential queue. - Upon reconnecting to the internet,
ReconnectAppand the queuedValidateSecondaryLoginAPI response execute simultaneously, firing a flurry of batch state updates (reconnecting network state, root navigation state re-evaluations, and Onyx logins updates). - During this batch update on Android,
useDynamicBackPath(DYNAMIC_ROUTES.CONTACT_METHOD_DETAILS.path)momentarily resolves against a transitional root state or fails insideNavigation.goBack(listPath)(logging[Navigation] Unable to go up). - Because
loginData?.validatedDateis now populated, on the immediate subsequent renderprevValidatedDateis no longer falsy. Consequently, the conditionif (prevValidatedDate || !loginData?.validatedDate)evaluates to true and permanently exits the effect without ever attempting navigation again. - The screen therefore stays mounted and renders the validated contact method details view (
getMenuItems()).
What changes do you think we should make in order to solve the problem?
- In
src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx:- Track validation transition using a dedicated ref (
hasHandledValidationNavigation = useRef(false)) initialized to!!loginData?.validatedDateon mount. - When the screen mounts on an unvalidated contact method and later receives
validatedDate, compute the explicit fallback route rather than relying solely on global focused navigation state. - Ensure that if
Navigation.goBack(listPath)fails or if the screen transitions to validated state while mounted from the verification form, we fallback to navigating explicitly toROUTES.SETTINGS_CONTACT_METHODS.routeor invokeNavigation.goBack().
const hasHandledValidationNavigation = useRef(!!loginData?.validatedDate); useEffect(() => { if (hasHandledValidationNavigation.current || !loginData?.validatedDate) { return; } hasHandledValidationNavigation.current = true; if (isFocused) { Navigation.goBack(listPath || ROUTES.SETTINGS_CONTACT_METHODS.route); } else { setShouldNavigateOnFocus(true); } }, [loginData?.validatedDate, isFocused, listPath]); - Track validation transition using a dedicated ref (
- In the focus restoration effect:
useEffect(() => { if (!isFocused || !shouldNavigateOnFocus) { return; } setShouldNavigateOnFocus(false); Navigation.goBack(listPath || ROUTES.SETTINGS_CONTACT_METHODS.route); }, [isFocused, shouldNavigateOnFocus, listPath]);
What alternative solutions did you explore? (Optional)
Using a timeout or polling. Rejected because cleanly tracking the initial mount validation state via ref and providing a reliable fallback to ROUTES.SETTINGS_CONTACT_METHODS.route directly resolves the root cause deterministically without arbitrary delays.
Automated Tests
In tests/unit/DynamicContactMethodDetailsPageTest.tsx:
- Render
DynamicContactMethodDetailsPagewith an unvalidated contact method (validatedDate: undefined). - Simulate network reconnection by updating Onyx
ONYXKEYS.LOGINSwith a populatedvalidatedDate. - Assert that
Navigation.goBackis called with the contact methods list path.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0170d6b02e9440e604
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
When a secondary contact method is added while offline, the user enters the magic code, reconnects, and the validation succeeds - but the user is left on the contact method details screen (which flips to its validated view) instead of being navigated back to the contact methods list.
What is the root cause of that problem?
The only navigation trigger is the one-shot effect in DynamicContactMethodDetailsPage.tsx:137-151, which fires when validatedDate transitions from empty to set (guarded by usePrevious):
if (prevValidatedDate || !loginData?.validatedDate) {
return;
}
if (isFocused) {
Navigation.goBack(listPath);
} else {
setShouldNavigateOnFocus(true);
}
Two problems make this fail permanently in the offline flow:
-
The destination is computed from global navigation state at the worst moment.
listPathcomes fromuseDynamicBackPath(DYNAMIC_ROUTES.CONTACT_METHOD_DETAILS.path), which serializes the whole root navigation tree at the currently focused route (useRootNavigationState) and derives the back path from whichever route happens to be focused. In the offline flow, the queuedValidateSecondaryLoginresponse lands in the same batch as theReconnectAppreconnect data, so on Android the root navigation state is mid-transition when the effect fires.goBack(listPath)then silently no-ops (logging[Navigation] Unable to go up) or targets the wrong route. -
A failed attempt is never retried. On the next render
prevValidatedDateis already truthy, so the guardif (prevValidatedDate || !loginData?.validatedDate)exits the effect forever. The existingshouldNavigateOnFocusfallback only covers the case where the screen was not focused when the effect fired - it does not cover a focused-screengoBackthat silently failed.
What changes do you think we should make in order to solve the problem?
- In
DynamicContactMethodDetailsPage.tsx, navigate tobackTo(already computed at line 85:getPathWithoutDynamicSuffix(listPath, DYNAMIC_ROUTES.CONTACT_METHODS.path) || ROUTES.SETTINGS_PROFILE.route) instead of the rawlistPath.backToderives the contact-methods list destination from this screen's own route, so it is stable even when the global focused route is transitional during the reconnect batch. - Replace the
usePreviousone-shot guard with a ref latch (hasNavigatedOnValidation) that flips only after thegoBackcall is actually issued. In the existing focus-restoration effect, retry the navigation ifloginData.validatedDateis set, the latch is not set, and the screen is focused - so a no-op during the reconnect batch is retried once navigation settles. Keep the existing unfocused-case fallback (shouldNavigateOnFocus) as-is.
What alternative solutions did you explore? (Optional)
Delaying the navigation with a timeout until the reconnect batch settles. Rejected: arbitrary delays are flaky on slow devices, and the deterministic route plus retry latch fixes the root cause without timing hacks.
Automated Tests
In tests/unit/DynamicContactMethodDetailsPageTest.tsx:
- Render
DynamicContactMethodDetailsPagewith an unvalidated contact method (validatedDateundefined). - Simulate the reconnect batch by updating Onyx
ONYXKEYS.LOGINSwith a populatedvalidatedDatewhile the root navigation state is transitional. - Assert
Navigation.goBackis called with the contact methods list path (not the raw globallistPath). - Simulate a failed first attempt (goBack no-op) followed by a refocus, and assert the navigation is retried.
Contributor details Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~011091133bbb09cd1c
Proposal
Please re-state the problem that we are trying to solve in this issue.
When adding a secondary contact method offline and entering the magic code, once the device reconnects to the internet and validation succeeds, the user is not navigated back to the contact methods list and is left stranded on the contact method details menu view.
What is the root cause of that problem?
In src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx:
- One-shot guard via
usePrevious: The validation navigation effect (lines 137–151) is guarded byif (prevValidatedDate || !loginData?.validatedDate).usePreviousupdates its internal ref during an effect; oncevalidatedDatepopulates,prevValidatedDatebecomes truthy on the immediate next render. If the navigation call is delayed or dropped during network reconnection, or ifshouldNavigateOnFocusis set, the guard exits permanently on all subsequent renders and navigation is never re-attempted. - Omitted dependency in focus effect:
In the focus restoration effect (lines 154–161),
shouldNavigateOnFocusis omitted from the dependency array ([isFocused]). IfshouldNavigateOnFocusis set totruewhileisFocusedremainstrue(e.g., toggling Wi-Fi via Android quick settings / status bar without an actual route transition), the effect never fires. - Reactive
listPathinstability during reconnection:listPathis derived fromuseDynamicBackPath(DYNAMIC_ROUTES.CONTACT_METHOD_DETAILS.path). During the reconnection batch update (ReconnectApp+ValidateSecondaryLogin), root navigation state can be transitional, causinguseDynamicBackPathto fall back toROUTES.HOMEor no-op ondistanceToPop <= 0. - Premature view flip:
isValidateCodeFormVisibleis updated purely on!loginData?.validatedDate(lines 163–165). As soon asvalidatedDatearrives, it flips to rendergetMenuItems()before the screen is popped, leaving the details options visible to the user.
What changes do you think we should make in order to solve the problem?
- In
src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx:- Compute the canonical contact methods list route using
createDynamicRoute:
This matches the pattern established inconst contactMethodsListRoute = useMemo( () => createDynamicRoute(DYNAMIC_ROUTES.CONTACT_METHODS.path, backTo), [backTo], );SetDefaultContactMethodConfirmValidateCodePage.tsx:47and guarantees the destination is always deterministic regardless of transient root navigation state. - Replace
usePreviouswith a ref tracking validation navigation state (hasNavigatedAfterValidation = useRef(!!loginData?.validatedDate)), matching the pattern established inVerifyAccountPageBase.tsx:76. - Update the validation navigation effect to navigate to
contactMethodsListRoutewhenisFocusedis true, or setshouldNavigateOnFocus(true)if not focused:useEffect(() => { if (!loginData?.validatedDate || hasNavigatedAfterValidation.current) { return; } if (isFocused) { hasNavigatedAfterValidation.current = true; Navigation.goBack(contactMethodsListRoute); } else { setShouldNavigateOnFocus(true); } }, [loginData?.validatedDate, isFocused, contactMethodsListRoute]); - In the focus restoration effect, include
shouldNavigateOnFocusin the dependencies and invokeNavigation.goBack(contactMethodsListRoute)when focus is active and validation is complete:useEffect(() => { if (!isFocused || !shouldNavigateOnFocus || hasNavigatedAfterValidation.current) { return; } hasNavigatedAfterValidation.current = true; setShouldNavigateOnFocus(false); Navigation.goBack(contactMethodsListRoute); }, [isFocused, shouldNavigateOnFocus, contactMethodsListRoute]); - Only render
getMenuItems()if the screen was already mounted with a validated contact method, avoiding the visual flash when popping upon newly completed validation.
- Compute the canonical contact methods list route using
What alternative solutions did you explore? (Optional)
- Navigating directly to
backTo: Rejected becausebackTois the profile root (settings/profile), which skips the contact methods list and pops two screens instead of one. - Using a timeout or delay: Rejected because timing-based solutions are non-deterministic across devices; using a ref latch with deterministic route construction directly eliminates the race condition.
Automated Tests
In tests/unit/DynamicContactMethodDetailsPageTest.tsx:
- Render
DynamicContactMethodDetailsPagewith an unvalidated contact method. - Update Onyx
ONYXKEYS.LOGINSwith a populatedvalidatedDatewhileisFocused = false. - Assert
Navigation.goBackis not called yet. - Switch
isFocused = trueand assertNavigation.goBackis called with the contact methods list route.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0163955a2ba221e513
Proposal
Please re-state the problem that we are trying to solve in this issue.
When adding a secondary contact method while offline and submitting the magic code, once the device reconnects to the internet and validation succeeds, the user is not navigated back to the contact methods list and remains on the contact method details screen (which transitions into its validated state).
What is the root cause of that problem?
In src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx:133-161:
- Unstable target route during reconnect batching:
The validation success navigation effect calls
Navigation.goBack(listPath)wherelistPathis derived fromuseDynamicBackPath(DYNAMIC_ROUTES.CONTACT_METHOD_DETAILS.path).useDynamicBackPathcomputes the path by serializing the global root navigation tree viauseRootNavigationState. When the app reconnects to the network,ReconnectAppand queued API responses execute in the same tick. The router state is temporarily transitional, causingNavigation.goBack(listPath)to silently fail with[Navigation] Unable to go upor evaluate to an invalid dynamic path. Conversely, line 85 already definesbackTo = getPathWithoutDynamicSuffix(listPath, DYNAMIC_ROUTES.CONTACT_METHODS.path) || ROUTES.SETTINGS_PROFILE.route, which provides a clean static fallback target. - One-shot guard with
usePreviousprevents retry on drop: The effect is guarded by:if (prevValidatedDate || !loginData?.validatedDate) { return; }usePreviousupdates its internal ref on each render cycle. OncevalidatedDatearrives in Onyx,prevValidatedDatebecomes truthy on the immediate next render. If thegoBackcall fails or is dropped during the reconnect transition, the effect never re-runs, stranding the user on the contact method details view.
What alternative solutions did you explore? (Optional)
None, ensuring route target stability via backTo and using an explicit navigation latch ref is the robust pattern.
What changes do you think we should make in order to solve the problem?
In src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx:
- Use a ref latch (
hasNavigatedOnValidation) instead of relying solely onusePrevious. - Target
backTo(orlistPathwithbackTofallback) rather than barelistPath:
--- a/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx
+++ b/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx
@@ -134,18 +134,22 @@ function DynamicContactMethodDetailsPage({route}: DynamicContactMethodDetailsPage
const isFocused = useIsFocused();
const [shouldNavigateOnFocus, setShouldNavigateOnFocus] = useState(false);
+ const hasNavigatedOnValidation = useRef(false);
useEffect(() => {
- if (prevValidatedDate || !loginData?.validatedDate) {
+ if (hasNavigatedOnValidation.current || !loginData?.validatedDate) {
return;
}
if (isFocused) {
+ hasNavigatedOnValidation.current = true;
// Navigate to methods page on successful validateCode verification.
// The validatedDate property indicates successful validateCode verification.
- Navigation.goBack(listPath);
+ Navigation.goBack(backTo);
} else {
// Set flag to navigate when screen regains focus
setShouldNavigateOnFocus(true);
}
- }, [prevValidatedDate, loginData?.validatedDate, isDefaultContactMethod, listPath]);
+ }, [loginData?.validatedDate, isFocused, backTo]);
// Handle navigation when screen regains focus and flag is set
useEffect(() => {
@@ -155,7 +159,8 @@ function DynamicContactMethodDetailsPage({route}: DynamicContactMethodDetailsPage
}
setShouldNavigateOnFocus(false);
- Navigation.goBack(listPath);
+ hasNavigatedOnValidation.current = true;
+ Navigation.goBack(backTo);
}, [isFocused, shouldNavigateOnFocus, backTo]);
What automated tests can you add to prevent this from re-occurring?
Add a unit test in tests/unit/pages/DynamicContactMethodDetailsPageTest.tsx simulating:
- Entering magic code offline (login marked pending).
- Simulating reconnect batch updating
loginData.validatedDatewhileDynamicContactMethodDetailsPageis mounted. - Asserting that
Navigation.goBack(backTo)is called, returning the user to the contact methods list.
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
@getusha Whoops! This issue is 2 days overdue. Let's get this updated quick!
:sos: C+ Help Wanted
🚨 Edited by proposal-police: This proposal was edited at 2026-10-26 10:35:25 UTC.
Proposal
Please re-state the problem that we are trying to solve in this issue.
After validating a new secondary contact method that was entered while offline, going back online from the Test Preferences modal leaves the user on the (now validated) contact method details page instead of taking them back to the contact methods list.
What is the root cause of that problem?
Going frame by frame through the attached video (around 2:36 to 2:41) shows what actually happens:
- "Force offline" is switched off inside the Test Preferences modal, the queued code is sent and the page behind the modal flips to the validated view ("Set as default").
- The tester taps outside, the modal closes and the details page shows for a single frame.
- Right away the Test Preferences modal opens again, and this time the Profile page is behind it, the details page is gone.
- The tester taps outside again and lands on a freshly mounted details page that is already validated, so nothing navigates anymore. Back from there goes to Profile, the list is gone (2:52).
So goBack isn't silently failing or being dropped. It runs, but with the wrong target.
The code is only sent on reconnect, which here happens while the modal is open: https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/components/ValidateCodeInput.tsx#L237-L253
While the modal is open the details page is not focused, so the validation effect only sets shouldNavigateOnFocus and the navigation is deferred to the focus effect:
https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L133-L161
Both effects navigate to listPath, which isn't derived from this screen. It's the path of whatever route is focused in the whole root state, with our suffix stripped only if it happens to be at the end:
https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L80-L81
https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/hooks/useDynamicBackPath.ts#L23-L37
While the modal is on top, the focused path is test-tools?backTo=settings/profile/contact-methods/<email>/details (the modal is opened with the current route as backTo). It doesn't end with :contactMethod/details, so the strip does nothing and listPath becomes the test tools URL.
When the modal closes, isFocused and listPath don't update in the same render:
useIsFocusedis auseSyncExternalStoreover the navigator'sfocus/blurevents (useIsFocused.tsx#L44). The navigator emitsfocusfrom its own effect and the store update re-renders synchronously.listPathis plainuseStateset from the container'sstatelistener (useRootNavigationState.ts#L34-L43), and the container emitsstatefrom its ownuseEffect(BaseNavigationContainer.tsx#L418). The container is the parent, so that runs after the navigator's effects, and it lands one render later.
The focus effect only depends on isFocused, so it runs exactly once, in the render where focus has already flipped but listPath is still the modal URL, and calls Navigation.goBack('test-tools?backTo=...details'). The test tools navigator was just popped, so goUp can't find it in the root state and replaces instead:
https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/libs/Navigation/Navigation.ts#L612-L618
That replaces the whole RHP (list + details) with a new Test Preferences modal, which is why the modal "reopens" over Profile. Closing it calls goBack(backTo) with the details URL it was originally opened from:
https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/libs/actions/TestTool.ts#L27-L33
That URL isn't in the stack anymore either, so a new details page is pushed. It mounts with validatedDate already set, so prevValidatedDate is set on the first render and the validation effect never navigates. The user is stuck on the details page, which matches "User is getting navigated to the contact method details screen".
This started when #97526 replaced the static ROUTES.SETTINGS_CONTACT_METHODS.getRoute(backTo), which #81673 used for this same focus fallback (twin issue #81043), with the root-state-derived listPath. The static route couldn't change while the screen was covered, the new one does.
What changes do you think we should make in order to solve the problem?
Resolve the list path at the moment we navigate, not from the render that happened to flip isFocused. When the focus effect runs, the root state is already committed with this screen focused (getRootState() reads the live navigator state). Only the state event that refreshes listPath is late.
useDynamicBackPath is just getPathFromState(rootState) + stripDynamicRouteSuffixFromPath, and both already exist as plain functions (Navigation.getActiveRoute() is exactly getPathFromState(navigationRef.getRootState())):
https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/libs/Navigation/helpers/getActiveRoute.ts#L8-L25
So in DynamicContactMethodDetailsPage add a small helper and use it for the two validation navigations (the isFocused branch of the validation effect and the shouldNavigateOnFocus effect):
// Read the path when navigating, the rendered listPath can still be the route of a screen just closed over this one
const goBackToContactMethods = () => {
Navigation.goBack(stripDynamicRouteSuffixFromPath(Navigation.getActiveRoute(), DYNAMIC_ROUTES.CONTACT_METHOD_DETAILS.path));
};
That's the whole fix. It doesn't depend on which of isFocused / listPath re-renders first, so it doesn't rely on React's render ordering at all. The header back button and the other goBack(listPath) calls are user taps on a focused page where listPath is already current, so they stay as they are, and useDynamicBackPath (used in 240+ files) isn't touched.
I have the fix with tests here, the new test fails on main and passes with the change: Compare branch: https://github.com/Expensify/App/compare/main...David-2002065:App:fix/104461-contact-method-stale-list-path
What alternative solutions did you explore? (Optional)
-
Bind the list path to this screen instead of the focused root route, the same way
useScreenBoundDynamicRoutedoes "so a link built during render survives another screen being stacked over it": https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/hooks/useScreenBoundDynamicRoute.ts#L16-L45 That means syncing the path only while this route is focused and stripping our suffix from it. It covers everylistPathuse on the page, but it's more code than this bug needs. Doing the same insideuseDynamicBackPathitself (remembering the last matched value) fixes the whole class, but it changes what a shared hook returns for every screen that's covered by something, which is a much bigger blast radius for a one-screen report. -
Keep
listPath, but make the focus effect also depend onlistPathand wait for it to catch up before navigating. This works today, but it's correct only because the container'sstateeffect happens to land after the navigator'sfocusevent. If those ever arrive in the other order (or in the same render), the effect has to be written carefully to not miss the navigation, while reading the live state at call time doesn't care.
A ref latch, a retry, or a fallback like listPath || ROUTES.SETTINGS_CONTACT_METHODS.route doesn't help here: goBack doesn't fail or bail out, it succeeds with the test tools URL (which isn't empty), and the remounted page has already lost its shouldNavigateOnFocus state anyway.
Automated Tests
In tests/unit/DynamicContactMethodDetailsPageTest.tsx (already in the branch):
- Render with an unvalidated login while another screen covers the page (
isFocused = false,useDynamicBackPathreturningtest-tools?backTo=...details). MergevalidatedDateand checkNavigation.goBackisn't called yet. - Flip
isFocusedtotruewhile the hook still returns the stale modal path but the live route is the details page (the render where focus flips first). CheckgoBackis called once withsettings/profile/contact-methodsand not the test tools URL. This fails on main. - The existing focused case (validated while the page is focused) still calls
goBack. - Opening an already validated contact method doesn't call
goBack.
Test run
npx jest tests/unit/DynamicContactMethodDetailsPageTest.tsx
main:
✕ goes back to the contact methods list when the screen is refocused after being validated under another screen
Expected: "settings/profile/contact-methods"
Received: "test-tools?backTo=settings/profile/contact-methods/fake%40gmail.com/details"
Tests: 1 failed, 4 passed, 5 total
branch:
Tests: 5 passed, 5 total
Proposal
Please re-state the problem that we are trying to solve in this issue.
After pasting the magic code while offline and going back online, the contact method is validated but the user is not taken back to the contact methods list. They stay on the details screen, now in its validated state.
What is the root cause of that problem?
The deferred "go back on focus" navigation runs one render too early, with a back path that still points at the Test tools modal, so goBack replaces the settings RHP with that modal instead of popping to the list.
- Offline, the code is not submitted:
ValidateCodeInputreturns early onisOfflineand re-submits inonReconnect(https://github.com/Expensify/App/blob/b0238c54ff2b733782ae5c35d3618708924be195/src/components/ValidateCodeInput.tsx#L237-L262). So the request goes out the moment "Force offline" is switched off, while the Test tools modal is still open above the page. ValidateSecondaryLoginsucceeds and setsvalidatedDate. The page's effect sees the transition, but the screen is not focused (the modal is a root-stack route above the RHP), so it only setsshouldNavigateOnFocus(https://github.com/Expensify/App/blob/b0238c54ff2b733782ae5c35d3618708924be195/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L137-L151). The page flips to its validated view behind the modal at 2:37.8 in the video.- When the modal is dismissed, the second effect fires on
isFocusedand callsNavigation.goBack(listPath)(https://github.com/Expensify/App/blob/b0238c54ff2b733782ae5c35d3618708924be195/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L153-L161).listPathcomes fromuseDynamicBackPath, which is derived from whichever route is focused in the whole tree and returns the path unchanged when the:contactMethod/detailssuffix does not match (https://github.com/Expensify/App/blob/b0238c54ff2b733782ae5c35d3618708924be195/src/hooks/useDynamicBackPath.ts#L24-L44). While the modal was focused that value wastest-tools?backTo=settings/profile/contact-methods/.../details. - The effect's two inputs update in different renders.
useIsFocusedis auseSyncExternalStoreover the live navigation state, so it re-renders synchronously as soon as the modal is popped.listPathis plainuseStatefed by the container'sstateevent, which the container emits from its own effect, one render later (https://github.com/Expensify/App/blob/b0238c54ff2b733782ae5c35d3618708924be195/src/hooks/useRootNavigationState.ts#L20-L45). Keyed onisFocusedalone, the effect runs whilelistPathis still the modal path. goBack('test-tools?...')targets a route that is no longer in the root state, sogoUpdispatches REPLACE at the root (https://github.com/Expensify/App/blob/b0238c54ff2b733782ae5c35d3618708924be195/src/libs/Navigation/Navigation.ts#L604-L609), replacing the RHP (list + details) with the Test tools modal. The video shows this: the modal closes at 2:39.3 and re-opens one frame later over Profile, because the RHP is gone.- Dismissing the modal again runs
Navigation.goBack(backTo)with the details path stored in the modal's params (https://github.com/Expensify/App/blob/b0238c54ff2b733782ae5c35d3618708924be195/src/libs/actions/TestTool.ts#L27-L31). That route is gone too, so it is pushed fresh: the user lands on the details screen with no list beneath it, and back goes to Profile (2:52 in the video).
This is a regression from PR #97526 (b980c643331). The fix for the twin issue #81043 (PR #81673) built the target from route.params.backTo, which could not change while the screen was covered. #97526 swapped it for useDynamicBackPath, which follows global focus and lags it by one render.
What changes do you think we should make in order to solve the problem?
Key the deferred navigation on the back path catching up with the focus change, not on the focus change itself. In DynamicContactMethodDetailsPage.tsx change the second effect's dependency list from [isFocused] to [listPath, shouldNavigateOnFocus]:
useEffect(() => {
if (!isFocused || !shouldNavigateOnFocus) {
return;
}
setShouldNavigateOnFocus(false);
Navigation.goBack(listPath);
// listPath lags isFocused by a render (state event vs. sync focus read), so wait for it
}, [listPath, shouldNavigateOnFocus]);
Why this is enough: the flag is only set while the screen is covered, so listPath at that time is the covering route's path. When the cover is removed the focused path becomes this screen's own path, so listPath always changes, and only after isFocused is already true (the container emits state after every navigator's focus effects). The effect runs once with isFocused === true and the correct list path. If both update in the same render it still works, since listPath is a dep. The online path is untouched: the first effect still navigates immediately while focused, and every other goBack(listPath) in the page is user-initiated while focused, where listPath is current.
Why the obvious alternatives fail: adding isFocused to the deps, or useFocusEffect, fires in the same early render (focus events come from navigator effects, which run before the container's state effect) and goes back to the same stale path. A fallback like listPath || ROUTES.SETTINGS_CONTACT_METHODS.route never triggers, because listPath is not empty, it is the modal path.
What alternative solutions did you explore? (Optional)
- Track "did this page submit a code" with a ref and navigate on
validatedDate. The video shows the navigation already fires; its target is wrong, so this changes nothing on the repro. - Read the path live inside the effect (
Navigation.getActiveRoute()plus the suffix strip fromuseDynamicBackPath). Correct, but duplicates the hook's logic in the page for one call site. - Make
useDynamicBackPathkeep its last matching value when the focused route is not the caller's. Fixes the class for all consumers, but changes a shared hook for a one-screen report.
Proposal
Please re-state the problem that we are trying to solve in this issue.
On the contact method details page, you open an unvalidated secondary contact method, go offline, and paste the magic code. While offline the verification can't be sent, so nothing happens (expected). When you re-enable the internet, the verification is submitted and the contact method gets validated — but instead of being taken back to the contact methods list, you are left on the contact method details screen (now showing the validated "Set as default / Remove" view).
What is the root cause of that problem?
1. While offline, the magic code is not submitted — the submission is deferred until the device reconnects.
ValidateCodeInput refuses to auto-submit while offline (|| isOffline in the validateAndSubmit guard), and instead registers the same validateAndSubmit as the onReconnect callback of useNetwork. So when the user pastes the code offline, nothing is sent; the actual validateSecondaryLogin call only fires once the network comes back.
https://github.com/Expensify/App/blob/fa269bae19c71e05e78fd54dc85d8a3acb90c88e/src/components/ValidateCodeInput.tsx#L237-L253
2. The contact method is marked validated only in the success response, which arrives after reconnect.
validateSecondaryLogin sets validatedDate in successData (not in optimisticData). Because the submission itself is deferred to reconnect, loginData.validatedDate flips from empty to set during the reconnect cycle, not while the user is actively interacting with the form.
https://github.com/Expensify/App/blob/fa269bae19c71e05e78fd54dc85d8a3acb90c88e/src/libs/actions/User.ts#L647-L661
3. The "go back to the list" navigation is driven by watching that validatedDate flip, and its fallback for the "not focused at the moment of validation" case is broken.
In DynamicContactMethodDetailsPage, the first effect navigates back to the list the moment validatedDate becomes set — but only if isFocused is true at that render. If the screen is not focused at that render (which is exactly what happens when validation resolves during the reconnect cycle rather than during a live user interaction), it instead takes the else branch and sets a shouldNavigateOnFocus flag, expecting a second effect to complete the navigation later.
The second effect is meant to perform that deferred navigation, but its dependency array is [isFocused] only. It therefore runs only when isFocused changes value — never when shouldNavigateOnFocus flips from false to true. So in the reconnect path, the flag is set but the fallback effect never fires, the goBack is silently dropped, and the user is stranded on the details page (which has meanwhile switched to its validated view via the setIsValidateCodeFormVisible(!loginData?.validatedDate) effect).
https://github.com/Expensify/App/blob/fa269bae19c71e05e78fd54dc85d8a3acb90c88e/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L137-L161
What changes do you think we should make in order to solve the problem?
Fix the fallback effect so it actually fires when the deferred-navigation flag is set, not only on focus transitions. Add shouldNavigateOnFocus (and listPath, which the effect uses) to its dependency array. With the flag now in the deps, the effect runs as soon as the first effect sets it, and — because the screen is already focused on reconnect — immediately navigates back to the contact methods list. The existing setShouldNavigateOnFocus(false) + the prevValidatedDate guard already prevent any double navigation when listPath recomputes after goBack.
https://github.com/Expensify/App/blob/fa269bae19c71e05e78fd54dc85d8a3acb90c88e/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L154-L161
}, [isFocused, shouldNavigateOnFocus, listPath]);
The react-hooks/exhaustive-deps disable comment above the array can be removed, since all referenced values (isFocused, shouldNavigateOnFocus, listPath) are now listed (setShouldNavigateOnFocus and Navigation are stable).
🚨 Edited by proposal-police: This proposal was edited at 2026-10-26 10:01:25 UTC.
Proposal
Please re-state the problem that we are trying to solve in this issue.
An unvalidated contact method opens on the magic-code screen (the contact method details page). The user goes offline, pastes the magic code, then restores the internet connection. Once the queued validation completes, the user should be navigated back to the contact methods list, but on Android they end up on the contact method details screen instead.
What is the root cause of that problem?
Two pieces combine.
First, pasting a complete code submits the form even while offline. The code input's fulfill handler calls the submit callback directly, bypassing the offline-disabled Verify button, so validateSecondaryLogin is queued by the offline request queue:
https://github.com/Expensify/App/blob/9d14b70be07d516add0a1fe43c06aef15bec321e/src/components/ValidateCodeActionModal/ValidateCodeForm/BaseValidateCodeForm.tsx#L329-L339
Because of that, the success data that stamps validatedDate on the login only arrives after connectivity returns — and at that moment the details screen is no longer the focused route. In the issue's video the connection is restored through the test-tools modal, which is a route stacked on top of the root navigator; any screen stacked over the details page when the queued request completes triggers the same failure.
Second, the back target used by the navigate-on-success logic is wrong whenever the details screen is covered. The page computes its back path with useDynamicBackPath:
https://github.com/Expensify/App/blob/9d14b70be07d516add0a1fe43c06aef15bec321e/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L80-L85
That hook derives the back path from the path of the currently focused route in the root navigation state. When another screen sits on top, the focused path no longer ends with the :contactMethod/details suffix, the suffix match fails, and the hook falls through to returning the covering route's own path unchanged:
https://github.com/Expensify/App/blob/9d14b70be07d516add0a1fe43c06aef15bec321e/src/hooks/useDynamicBackPath.ts#L25-L43
So when validatedDate lands while the screen is covered, the navigate-on-success effects consume a listPath that points at the covering screen rather than the contact methods list:
https://github.com/Expensify/App/blob/9d14b70be07d516add0a1fe43c06aef15bec321e/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L133-L161
Calling Navigation.goBack with that path resolves to the route that is already focused, so the navigation silently does nothing — and because the effect is guarded by prevValidatedDate, it is a one-shot that never retries. The user is never returned to the contact methods list; when the covering screen closes they land back on the contact method details screen, which now shows the validated state ("Set as default" / "Remove"). That is exactly the reported actual result.
What changes do you think we should make in order to solve the problem?
Make useDynamicBackPath screen-bound, in the same spirit as useScreenBoundDynamicRoute for forward routes: remember the last back path computed while the expected dynamic suffix actually matched the focused path (i.e. while the owning screen was the focused route), and when the suffix no longer matches — because another screen is stacked on top — keep returning that remembered value instead of falling back to the covering route's path. Only if the suffix has never matched does the hook keep today's fallback of returning the path as-is. The forward-route hook already documents this exact trap — a route built during render but followed later must not resolve against whatever happens to be focused at that time:
https://github.com/Expensify/App/blob/9d14b70be07d516add0a1fe43c06aef15bec321e/src/hooks/useScreenBoundDynamicRoute.ts#L22-L47
With the retained value, the existing focused/unfocused handling in the details page works as designed on every platform: if validation succeeds while the screen is focused, it goes back to the list immediately; if it succeeds while the screen is covered, the shouldNavigateOnFocus flag fires on refocus with the correct list path and the user is returned to the contact methods list.
I also added a unit test to the existing useDynamicBackPath tests covering a route that gets covered by another screen and later refocused.
Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/104461-dynamic-back-path-covered-screen?expand=1
What alternative solutions did you explore? (Optional)
A scoped fix inside DynamicContactMethodDetailsPage only: snapshot listPath into a ref while the screen is focused (when the suffix match is valid) and have both navigate-on-success effects use that snapshot. This avoids touching the shared hook, but it leaves every other useDynamicBackPath consumer exposed to the same covered-screen staleness, so fixing the hook is preferable.
🤖 ProposalPolice™ is tracking duplicate proposals for this issue using an OpenAI Conversation. This comment stores that Conversation's ID and can be safely ignored.
Proposal updated — added compare branch with implementation.
🚨 Edited by proposal-police: This proposal was edited at 2026-10-26 17:21:13 UTC.
Proposal
Please re-state the problem that we are trying to solve in this issue.
After adding a secondary contact method, the user goes offline and pastes the magic code, then goes back online by switching off "Force offline" in the Test Tools modal (Cmd+D on Android). The user is expected to land on the contact methods list. Instead, the new email's details page ("Set as default" / "Remove") opens, and Back from it goes to Profile.
What is the root cause of that problem?
The root cause is useDynamicBackPath. It is meant to return the back path of the screen that calls it, but it builds that path from the focused route of the whole app. So whenever another screen is stacked on top of the caller, it returns a path that is not the caller's.
-
The details page builds its back path from the hook:
const listPath = useDynamicBackPath(DYNAMIC_ROUTES.CONTACT_METHOD_DETAILS.path);https://github.com/Expensify/App/blob/main/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx -
The hook reads the focused route of the whole app, and removes
:contactMethod/detailsfrom the end of it. If the end does not match, it returns the path unchanged: https://github.com/Expensify/App/blob/main/src/hooks/useDynamicBackPath.ts https://github.com/Expensify/App/blob/main/src/libs/Navigation/helpers/dynamicRoutesUtils/stripDynamicRouteSuffixFromPath.ts -
Test Tools opens on top with the current page in
backTo: https://github.com/Expensify/App/blob/main/src/libs/actions/TestTool.tsSo while it is open, the focused path is
test-tools?backTo=.../details. It does not end with/details, solistPathbecomes the Test Tools route. This is what the logs show:listPath settings/profile/contact-methods isFocused true (details page open) listPath settings/profile/contact-methods isFocused false (Test Tools opening) listPath test-tools?backTo=%2Fsettings%2Fprofile%2Fcontact-methods%2F<email>%2Fdetails isFocused false listPath test-tools?backTo=... isFocused true (Test Tools closing) -
With "Force offline" switched off inside Test Tools, the queued
ValidateSecondaryLoginfinishes.validatedDateis set while the page is covered (isFocusedis false). The page can't go back yet, so it only stores a flag:if (isFocused) { Navigation.goBack(listPath); } else { setShouldNavigateOnFocus(true); } -
When Test Tools closes, the focus effect runs
Navigation.goBack(listPath). ButlistPathis the Test Tools route, and it was just closed:if (!isFocused || !shouldNavigateOnFocus) return; Navigation.goBack(listPath); // listPath = 'test-tools?backTo=...' -
goUpcannot find that route in the navigation state, so it does aREPLACEinstead of a pop: https://github.com/Expensify/App/blob/main/src/libs/Navigation/Navigation.ts (canPopToRoute, thenREPLACE)That replaces the whole right-hand panel (the contact methods list and the details page) with Test Tools.
-
Closing Test Tools follows its
backTo, which is the details URL. That opens a new details page directly on top of Profile.validatedDateis already set, so we see "Set as default / Remove", and the list is gone from the stack.
It is not related to whether the account was validated first. It happens every time the connection is restored through Test Tools.
What changes do you think we should make in order to solve the problem?
Make useDynamicBackPath read the path of its own screen instead of the focused route of the app. The hook already runs inside the screen, so it knows its own route key (React Navigation's NavigationRouteContext). Nothing has to be remembered or guessed:
- Read the route key of the calling screen.
- Take the navigation state and drop every screen stacked above that route (Test Tools is one of them). This gives the state as it was before the modal opened.
- Build the path from that state and remove the suffix, as today.
With this, listPath is settings/profile/contact-methods the whole time, whether Test Tools is open or not. When Test Tools closes, Navigation.goBack(listPath) pops to the contact methods list.
Why this is the more direct fix: the root cause is "the hook looks at the wrong screen". This makes it look at the right one, so the path is always derived from the current state. There is no extra state to keep in sync, and it cannot go stale. It also fixes every other screen that calls the hook (more than 200), not only the details page.
New helper .../helpers/getStateFocusedOnRoute.ts:
function getStateFocusedOnRoute(state: State, routeKey: string): State | undefined {
for (const [index, route] of (state.routes ?? []).entries()) {
if (route.key === routeKey) {
// Found it: drop the routes above it and make it the focused one
return {...state, routes: state.routes.slice(0, index + 1), index};
}
// Look inside nested navigators, and do the same on the way back up
const nestedState = route.state ? getStateFocusedOnRoute(route.state, routeKey) : undefined;
if (nestedState) {
const routes = state.routes.slice(0, index + 1);
routes[index] = {...route, state: nestedState};
return {...state, routes, index};
}
}
return undefined;
}
Change in src/hooks/useDynamicBackPath.ts:
// `useRoute` throws outside a screen, so read the route from the context directly
const routeKey = useContext(NavigationRouteContext)?.key;
const path = useRootNavigationState((state) => {
if (!isEnabled || !state) {
return undefined;
}
// Build the path as if our screen were the focused one. Fall back to the real focused route
// if we are not in a screen, or not in the state yet.
const ownState = routeKey ? getStateFocusedOnRoute(state, routeKey) : undefined;
return getPathFromState(ownState ?? state);
});
// ...the rest of the hook is unchanged: HOME when there is no path, then strip the suffix
Edge cases
| Case | Result |
|---|---|
| Covered by a modal (Test Tools) | The covering screen is dropped, so the back path is the contact methods list (the bug fix) |
| Covered by several screens, or by another screen in the same stack | Same result, every screen above ours is dropped |
| Hook used outside a screen (no route in context) | Old behavior: uses the focused route |
| Screen not in the navigation state yet (still mounting) | Old behavior: uses the focused route, no crash |
| Navigation not ready (empty state) | The helper returns undefined, no crash |
Hook disabled (isEnabled = false) |
Reads nothing, returns HOME |
| Screen remounted | Nothing is stored in the hook, so there is nothing to lose |
| Screen is not covered | Same path as before the change, because our screen is already the focused one |
The navigation state is never changed. The helper returns a copy that is only used to build the path.
I checked it with the getStateFromPath and getPathFromState and the route names, with Test Tools stacked on top of the contact method details. Without the fix the hook returns exactly the value from the logs (test-tools?backTo=%2Fsettings%2Fprofile%2Fcontact-methods%2F...%2Fdetails). With the fix it returns the same path as when nothing is stacked on top.
What alternative solutions did you explore? (Optional)
Reminder: Please use plain English, be brief and avoid jargon. Feel free to use images, charts or pseudo-code if necessary. Do not post large multi-line diffs or write walls of text. Do not create PRs unless you have been hired for this job.
Result
https://github.com/user-attachments/assets/06008494-9c54-4652-8e98-1bea26128d78
🚨 Edited by proposal-police: This proposal was edited at 2026-10-26 11:05:04 UTC.
Proposal
Please re-state the problem that we are trying to solve in this issue.
After a secondary contact method’s security code is submitted by turning off Force offline inside the Test tools modal, closing the modal leaves the user on a newly opened contact method details page. The contact methods list has been removed from the stack, so Back goes to Profile.
What is the root cause of that problem?
The code is held until reconnect, and that reconnect happens while Test tools is the focused route. ValidateCodeInput returns early while offline and submits from onReconnect: https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/components/ValidateCodeInput.tsx#L237-L253
validatedDate is set on success. The details page is covered, so the validation effect only raises shouldNavigateOnFocus. The effect that runs when focus returns calls Navigation.goBack(listPath): https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L133-L161
listPath is the focused route in the whole tree, with this screen’s suffix removed only when that suffix is the tail: https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L80-L81 and https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/hooks/useDynamicBackPath.ts#L23-L37
An unmatched suffix is returned unchanged: https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/libs/Navigation/helpers/dynamicRoutesUtils/stripDynamicRouteSuffixFromPath.ts#L18-L25
Test tools is opened with the current route as backTo, so the focused path is test-tools?backTo=settings/profile/contact-methods/<email>/details. That path does not end in :contactMethod/details, and listPath becomes the Test tools URL: https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/libs/actions/TestTool.ts#L26-L44
useIsFocused updates in the render that pops the modal. listPath updates a render later, because useRootNavigationState only copies the path inside the state listener: https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/hooks/useRootNavigationState.ts#L35-L42
The focus effect therefore calls Navigation.goBack('test-tools?backTo=…details') after that route has already been popped. canPopToRoute is false when the route is absent, and goUp replaces the current route: https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/libs/Navigation/Navigation.ts#L444-L448 and https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/libs/Navigation/Navigation.ts#L614-L617
That replace removes the right-hand panel, which held both the list and the details page, and puts Test tools back. Closing it follows the modal’s backTo, the details URL, and mounts a new details page. usePrevious is initialized to the current validatedDate, so the one-shot effect does not navigate. The user is on the details screen, and Back goes to Profile.
What changes do you think we should make in order to solve the problem?
In DynamicContactMethodDetailsPage.tsx, build the list URL from the live route when navigating. Navigation.getActiveRoute() reads navigationRef.getRootState(), which is already the details page when the focus effect runs. The rendered listPath is the value that is one render behind.
+import stripDynamicRouteSuffixFromPath from '@libs/Navigation/helpers/dynamicRoutesUtils/stripDynamicRouteSuffixFromPath';
+const goBackToContactMethodsList = () => {
+ Navigation.goBack(stripDynamicRouteSuffixFromPath(Navigation.getActiveRoute(), DYNAMIC_ROUTES.CONTACT_METHOD_DETAILS.path));
+};
- Navigation.goBack(listPath);
+ goBackToContactMethodsList();
- Navigation.goBack(listPath);
+ goBackToContactMethodsList();
Use the helper in both validation effects. The focused branch needs it too, so a validation update that lands in the same render as the focus change cannot still close over the Test tools URL.
Header back and the other goBack(listPath) calls stay on listPath. They run from a tap while this page is focused, after the state listener has caught up. useDynamicBackPath is left alone.
Online verification is unchanged: the screen is focused, the live route ends in :contactMethod/details, and the strip result is the contact methods list. The case where a modal covers the page is unchanged in timing: navigation still waits for focus, then pops to the list instead of replacing the panel.
What alternative solutions did you explore? (Optional)
- Remembering the last matched back path inside
useDynamicBackPathfor every caller. That also keeps this page’slistPathstable while Test tools is open, and it changes the hook’s contract (“unmatched suffix returns the path as-is”) for every screen that uses it. - Re-running the focus effect when
listPathchanges, so it waits for the latestateevent. That works with today’s effect order and misses navigation if focus returns without anotherlistPathchange. - Delaying
goBack(listPath)until the next microtask. The call already runs. Its argument is the wrong route, so delaying it still replaces the panel. - Restoring
ROUTES.SETTINGS_CONTACT_METHODS.getRoute(backTo).backTois derived from the samelistPath, so while the modal is open it falls through to Profile and drops other entry points the dynamic route was added to support.
What specific scenarios should we cover in automated tests?
- With the page unfocused and
useDynamicBackPathreturningtest-tools?backTo=settings/profile/contact-methods/<email>/details, settingvalidatedDatedoes not callNavigation.goBack. - Flipping focus to true while that hook value is still the Test tools URL, and
Navigation.getActiveRoute()issettings/profile/contact-methods/<email>/details, callsNavigation.goBackonce withsettings/profile/contact-methods. - A focused page whose live route is the details URL still calls
Navigation.goBackwith the contact methods list whenvalidatedDatetransitions from empty to set. - Opening an already validated contact method does not call
Navigation.goBack.
Proposal
Please re-state the problem that we are trying to solve in this issue.
A secondary contact method is validated while offline. Once connectivity returns, the screen stays on the contact method details view (now showing Set as default / Remove) rather than popping back to the contact methods list.
What is the root cause of that problem?
validatedDate is only written in successData, so the whole sequence necessarily runs on reconnect — and in the OP's video the reconnect is done from inside the Test Tools modal ("Force offline"), which is the focused route at that moment. Stepping the video frame by frame: at ~2:38 the details page flips to Set as default / Remove behind the still-open modal, so the page has already observed validation and has taken the deferred branch added for #81043, storing a flag to go back once focus returns:
https://github.com/Expensify/App/blob/840dc3d45fcacc98b7205d06afd0fd55cc5cab0e/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L137-L161
The destination it will pass is listPath = useDynamicBackPath(...), and the hook's contract is the crux here: it matches registered dynamic suffixes against the tail of the globally focused route's path, and when no suffix matches it returns that active path verbatim:
https://github.com/Expensify/App/blob/840dc3d45fcacc98b7205d06afd0fd55cc5cab0e/src/hooks/useDynamicBackPath.ts#L33-L44
The Test Tools modal is opened with the active route embedded as backTo:
https://github.com/Expensify/App/blob/840dc3d45fcacc98b7205d06afd0fd55cc5cab0e/src/libs/actions/TestTool.ts#L41-L45
so while it is on top, the focused path is test-tools?backTo=settings/profile/contact-methods/<email>/details. :contactMethod/details is not the tail of that path, nothing matches, and the verbatim fallback hands back the modal's own route — listPath is now test-tools?backTo=….
Tapping outside closes the modal, the details screen refocuses, and the deferred effect dispatches Navigation.goBack('test-tools?backTo=…'). goUp can no longer find that route in the root state — it was just popped — so it takes the replace branch:
https://github.com/Expensify/App/blob/840dc3d45fcacc98b7205d06afd0fd55cc5cab0e/src/libs/Navigation/Navigation.ts#L603-L610
REPLACE on the root stack swaps the focused root route, and that route is RIGHT_MODAL_NAVIGATOR — which holds both the contact methods list and the details page — for TestToolsModalNavigator. The frames match that precisely: at ~2:39.4 the modal is fading out over the details page, and at ~2:39.5 it is fully back with Profile behind it, i.e. the Account tab's focused screen, all that is left once the entire RHP route is replaced. Closing the modal again runs Navigation.goBack(backTo) with backTo = the details path, which is why the user ends on the details page — and why Back from there goes to Profile later in the video: the list screen was destroyed along with the RHP stack, so there is nothing to pop to.
The forward direction of this same hazard is already handled in the codebase, bound to the screen "so a link built during render survives another screen being stacked over it":
https://github.com/Expensify/App/blob/840dc3d45fcacc98b7205d06afd0fd55cc5cab0e/src/hooks/useScreenBoundDynamicRoute.ts#L16-L26
useDynamicBackPath has no such binding, so the path it returns is only trustworthy while its own screen is the focused one. Online this never surfaces: the screen stays focused, listPath resolves normally and goBack pops to the list.
What changes do you think we should make in order to solve the problem?
Bind useDynamicBackPath to its own screen the same way: keep the last back path resolved from a path that actually carried the caller's suffix, and return that while another screen covers us. The current path stays the fallback for a screen that never matched, so a screen reached by a non-dynamic URL keeps today's value.
const pathWithoutLeadingSlash = (path ?? '').replaceAll(/^\/+/g, '');
const match = findAllMatchingDynamicSuffixes(pathWithoutLeadingSlash).find((m) => m.pattern === dynamicRouteSuffix);
const matchedBackPath = match ? getPathWithoutDynamicSuffix(match.pathUsedForMatching, match.actualSuffix, match.pattern) : undefined;
// The active path stops carrying our suffix as soon as another screen is stacked over this one, and
// callers that navigate after that (deferred/on-focus) must not be handed the covering screen's route.
const lastMatchedBackPath = useRef<Route | undefined>(undefined);
useEffect(() => {
if (!matchedBackPath) {
return;
}
lastMatchedBackPath.current = matchedBackPath;
}, [matchedBackPath]);
if (!path) {
return ROUTES.HOME;
}
return matchedBackPath ?? lastMatchedBackPath.current ?? (pathWithoutLeadingSlash as Route);
Storing from an effect rather than during render keeps this correct whichever order useIsFocused and useRootNavigationState settle in on the refocus render — a covering screen's path can never be stored. listPath then stays settings/profile/contact-methods, and the deferred goBack pops to the list, for every caller of the hook rather than this page alone.
Add a case to tests/navigation/useDynamicBackPathTests.ts asserting that after a state whose path carries the suffix, a later state whose path does not carry it still returns the matched back path instead of the new path.
What alternative solutions did you explore? (Optional)
Caching the resolved path inside DynamicContactMethodDetailsPage only. Rejected: every deferred or after-blur navigation built on useDynamicBackPath has the same hole, and a page-local copy has to guess which values are "ours", while the hook knows it from the suffix match.
Test branch: https://github.com/Expensify/App/compare/main...trasnake87:App:fix/104461
Regression test
tests/navigation/useDynamicBackPathTests.ts, run with npx jest tests/navigation/useDynamicBackPathTests.ts:
- without the change:
Tests: 1 failed, 22 passed, 23 total - with the change:
Tests: 23 passed, 23 total