[Due for payment 2026-11-14] [$250] [Sentry: APP-KC9] Navigation crash: 'filter' of undefined in getStateForRouteNamesChange
Sentry
https://expensify.sentry.io/issues/APP-KC9
Impact (snapshot at filing, 2026-10-12)
- Users (total since first seen): 43
- Users (last 30d, releases 9.5.5 to 9.5.7 only): 20
- Events (30d window): 83
- First seen: 2026-08-24
- Last seen: ongoing
- Platform: iOS hybrid app
- App version(s): 9.5.5
- Affected route(s): Search report (SearchReport)
- Mechanism: generic (unhandled TypeError during render)
Stack trace (top frames, first-party only)
PlatformNavigatorImpl
useNavigationBuilder
getStateForRouteNamesChange
Suspected cause
Navigator state has an undefined routes array when route names change, so .filter throws. It may relate to the react-navigation 7.x upgrade or to a screen mounting with a missing state.
Reproduction
Unknown. See the events linked from the Sentry issue.
Related
- Sibling Sentry IDs: none
- Prior GH issues: none found
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022109653565102124888
- Upwork Job ID: 2109653565102124888
- Last Price Increase: 2026-11-03
Issue Owner
Current Issue Owner: @mallenexpensifyIssue Owner
Current Issue Owner: @mallenexpensify
Triggered auto assignment to Contributor-plus team member for initial proposal review - @eh2077 (External)
Job added to Upwork: https://www.upwork.com/jobs/~022109653565102124888
(Vit's agent) @eh2077, there is no proposal on this issue yet. Can you look at the Sentry issue and tell us whether we should open it for contributors as it stands, or ask for expert contributor help because it needs deeper React Navigation knowledge?
⚠️ Preliminary analysis (low confidence): treat this as a starting point, not a conclusion.
The crash is in react-navigation's stock StackRouter.getStateForRouteNamesChange. It calls state.routes.filter(...) and state.preloadedRoutes.filter(...) without null checks (StackRouter.tsx:270-276, routers 7.6.4). No App router overrides this method.
It throws only when two things happen together:
- A navigator gets a stack state marked
stale: falsethat hasrouteNamesbut noroutesorpreloadedRoutes. - The navigator's screen list changes at the same time.
getRehydratedState returns stale: false states unchanged (StackRouter.tsx:205-207), so the incomplete state is never repaired.
The most likely place for the screen list to change is the root stack. It renders the onboarding navigator conditionally, and part of that condition is an imperative navigation-state read during render (AuthScreens.tsx:354). Swapping between AuthScreens and PublicScreens on HybridApp also changes the root's screen names.
I couldn't confirm the root cause because I couldn't find any App code that builds a state without routes or preloadedRoutes. Sentry was also unreachable from this run. To confirm, check the Sentry events for:
- The column number. It tells you whether line 270 (
routes) or line 276 (preloadedRoutes) throws. - Breadcrumbs just before the crash: onboarding completion, login or logout, OldDot↔NewDot switches, validate-login or 2FA flows.
Possible defensive fix: wrap getStateForRouteNamesChange in the App's custom routers so they default routes and preloadedRoutes to [], then call the stock router. StackRouter already handles an empty routes array. Also add a Log.hmmm call when either field is missing, so the source can be found.
Investigation details
- How a bad state reaches the router:
useNavigationBuilderuses astale: falsestate from the parent or container as-is. If itsrouteNamesdiffer from the rendered screens, it goes straight togetStateForRouteNamesChange. - App code that injects state: I checked these places. None of them drops
routesorpreloadedRoutes, but each passesstale: falsestate through without rehydrating it:- Preserved navigator states in
RightModalRouter,SearchFullscreenRouterandSplitRouter. - Root resets in
preMountBuffer.ts,Navigation.tsandNavigationRoot.tsx(after logout). - Tab state rebuilds in
GetStateForActionHandlers.ts.
- Preserved navigator states in
- Version note: the first-seen date (2026-08-24) falls in the 9.4.59–9.4.60 window. The react-navigation 7.22.1 upgrade landed after 9.5.5, so it isn't the trigger. The router code is identical in both versions.
- Related:
ScreenActivityWrapper(perf(navigation): add per-screen Activity behavior for covered screens, merged 2026-08-31) clears the parent'sroute.statewhen a covered screen is hidden. This makes state rebuilt fromgetRootState()more fragile, but it landed after the first-seen date. - No related open issues found.
Next Steps: Reply with @MelvinBot <your feedback> to refine this analysis.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~010e53044b5828fe60
Proposal
Please re-state the problem that we are trying to solve in this issue.
On iOS hybrid app (and across platforms during dynamic route/screen transitions such as mounting SearchReport), the app crashes with an unhandled TypeError: Cannot read properties of undefined (reading 'filter') inside getStateForRouteNamesChange called via PlatformNavigatorImpl > useNavigationBuilder.
What is the root cause of that problem?
In React Navigation 7.x (@react-navigation/routers/src/StackRouter.tsx:270-276), getStateForRouteNamesChange is invoked by useNavigationBuilder whenever a navigator's child route definitions change while retaining an existing state:
getStateForRouteNamesChange(state, { routeNames }) {
const routes = state.routes.filter(
(route) => routeNames.includes(route.name)
);
const preloadedRoutes = state.preloadedRoutes.filter(
(route) => routeNames.includes(route.name)
);
return {
...state,
routeNames,
routes,
preloadedRoutes,
index: Math.min(state.index, routes.length - 1),
};
}
Notice that state.routes.filter(...) and state.preloadedRoutes.filter(...) are invoked directly without null or undefined guards.
In Expensify, navigators are built using PlatformNavigatorImpl (src/libs/Navigation/PlatformStackNavigation/createPlatformStackNavigatorComponent/index.tsx and index.native.tsx). When a navigator receives a state marked stale: false (for example, during modal transitions, screen swapping between AuthScreens and PublicScreens on HybridApp, or preserved navigator states in SearchFullscreenRouter / RightModalRouter / SplitRouter) that has routeNames but where routes is undefined or incomplete, getRehydratedState leaves stale: false states unchanged (StackRouter.tsx:205-207).
When the navigator's screen list changes at that moment (such as when conditionally mounting screens), useNavigationBuilder directly invokes router.getStateForRouteNamesChange(state, { routeNames }). Because state.routes is undefined, state.routes.filter(...) throws an uncaught TypeError: 'filter' of undefined, causing the application to crash.
What changes do you think we should make in order to solve the problem?
We should implement a clean defensive wrapper at the platform stack navigator layer that protects all navigators across both web and native platforms:
1. Add wrapRouterWithSafeRouteNamesChange in createPlatformStackNavigatorComponent
In src/libs/Navigation/PlatformStackNavigation/createPlatformStackNavigatorComponent/index.tsx and index.native.tsx:
Define a safe router decorator:
import Log from '@libs/Log';
function wrapRouterWithSafeRouteNamesChange<TRouter extends Router<any, any>>(router: TRouter): TRouter {
const originalGetStateForRouteNamesChange = router.getStateForRouteNamesChange;
if (!originalGetStateForRouteNamesChange) {
return router;
}
return {
...router,
getStateForRouteNamesChange(state, options) {
const hasRoutes = Array.isArray(state?.routes);
const hasPreloadedRoutes = Array.isArray(state?.preloadedRoutes);
if (!hasRoutes || !hasPreloadedRoutes) {
Log.hmmm('[Navigation] getStateForRouteNamesChange received state with undefined routes/preloadedRoutes', {
hasRoutes,
hasPreloadedRoutes,
routeNames: options?.routeNames,
state,
});
}
const safeState = {
...state,
routes: hasRoutes ? state.routes : [],
preloadedRoutes: hasPreloadedRoutes ? state.preloadedRoutes : [],
};
return originalGetStateForRouteNamesChange(safeState, options);
},
};
}
2. Wrap createRouter in PlatformNavigatorImpl
In PlatformNavigatorImpl (index.tsx and index.native.tsx):
+ const safeCreateRouter = React.useCallback(
+ (routerOptions: RouterOptions) => wrapRouterWithSafeRouteNamesChange(createRouter(routerOptions)),
+ [createRouter],
+ );
const {
navigation,
state: originalState,
descriptors,
describe,
NavigationContent,
} = useNavigationBuilder<
PlatformStackNavigationState<ParamListBase>,
RouterOptions,
StackActionHelpers<ParamListBase>,
NativeStackNavigationOptions,
NativeStackNavigationEventMap,
PlatformStackNavigationOptions
>(
- createRouter,
+ safeCreateRouter,
{
id,
children,
screenOptions: {...defaultScreenOptions, ...screenOptions},
screenListeners,
initialRouteName,
sidebarScreen,
defaultCentralScreen,
parentRoute,
screenLayout,
},
convertToNativeNavigationOptions,
);
StackRouter naturally handles an empty routes array by clamping index: Math.min(state.index, routes.length - 1), safely averting the crash and allowing the rehydration pipeline to populate valid routes on the subsequent render pass, while logging diagnostic telemetry via Log.hmmm.
What alternative solutions did you explore? (Optional)
- Patching
@react-navigation/routersvia patch-package: We could add a patch topatches/react-navigation/for@react-navigation/routersmodifyingStackRouter.getStateForRouteNamesChangeto guard(state.routes ?? []).filter(...)and(state.preloadedRoutes ?? []).filter(...). While this patches upstream directly (consistent with our other react-navigation patches inpatches/react-navigation/details.md), wrapping it increatePlatformStackNavigatorComponentprovides immediate application-level protection withLog.hmmmdiagnostics telemetry to pinpoint any callers passing incomplete states, without having to maintain additional patch rebases on future react-navigation upgrades. Either approach (or combining both) is completely viable.
✅ 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.
[Sentry: APP-KC9] Unhandled TypeError: Cannot read properties of undefined (reading 'filter') occurring during navigation state route changes in getStateForRouteNamesChange when navigating to or mounting SearchReport inside PlatformNavigatorImpl.
What is the root cause of that problem?
The crash occurs due to a confluence between React Navigation 7's router implementation and Expensify's preserved navigator state lifecycle:
-
Unchecked array filter in
@react-navigation/routers: In@react-navigation/routers(StackRouter.tsx:270-276, v7.6.4),getStateForRouteNamesChangesynchronizes state when a navigator's route definition list changes:getStateForRouteNamesChange(state, { routeNames }) { const routes = state.routes.filter((route) => routeNames.includes(route.name) ); const preloadedRoutes = (state.preloadedRoutes ?? []).filter((route) => routeNames.includes(route.name) ); ... }Notice that while
preloadedRouteshas a fallback guard(state.preloadedRoutes ?? []),state.routeshas no guard at all. -
Why
SearchReporttriggers this in production: The Sentry issue explicitly identifiesSearchReporton iOS hybrid app. In Expensify:SearchReportresides insideRightModalNavigator(SCREENS.RIGHT_MODAL.SEARCH_REPORT, RightModalNavigator.tsx:516).RightModalNavigatorusesRightModalRouter(RightModalRouter.ts:15), which attempts to restore preserved state viagetPreservedNavigatorState(options.parentRoute.key).- When a preserved state is restored with
stale: false,getRehydratedStateinStackRouterreturns it untouched (StackRouter.tsx:205-207). - When screens are dynamically mounted or unmounted (e.g.
SearchReportanimated stacking or screen swaps),useNavigationBuilderdetects that the navigator's route definitions differ from the preserved state and invokesrouter.getStateForRouteNamesChange(state, { routeNames }). - If the preserved state lacks a populated
routesarray (or ifrouteswas cleared/omitted during parent state normalization),state.routes.filter(...)throws an unhandledTypeError: Cannot read properties of undefined (reading 'filter').
What changes do you think we should make in order to solve the problem?
We should implement a two-layer defense to guarantee both framework-level safety and application-level diagnostic monitoring:
1. Universal Guard in createPlatformStackNavigatorComponent
In src/libs/Navigation/PlatformStackNavigation/createPlatformStackNavigatorComponent/index.tsx and src/libs/Navigation/PlatformStackNavigation/createPlatformStackNavigatorComponent/index.native.tsx:
Wrap router.getStateForRouteNamesChange in a higher-order decorator wrapRouterWithSafeRouteNamesChange. This ensures that every stack navigator across the entire app (Root, RightModal, SearchFullscreen, Split, etc.) safely normalizes missing routes and logs actionable diagnostic telemetry via Log.hmmm:
import Log from '@libs/Log';
function wrapRouterWithSafeRouteNamesChange<TRouter extends Router<any, any>>(
router: TRouter,
displayName: string,
): TRouter {
const originalGetStateForRouteNamesChange = router.getStateForRouteNamesChange;
if (!originalGetStateForRouteNamesChange) {
return router;
}
return {
...router,
getStateForRouteNamesChange(state, options) {
const hasRoutes = Array.isArray(state?.routes);
const hasPreloadedRoutes = Array.isArray(state?.preloadedRoutes);
if (!hasRoutes || !hasPreloadedRoutes) {
Log.hmmm(`[${displayName}] getStateForRouteNamesChange received state with missing routes/preloadedRoutes`, {
displayName,
hasRoutes,
hasPreloadedRoutes,
routeNames: options?.routeNames,
state,
});
}
const safeState = {
...state,
routes: hasRoutes ? state.routes : [],
preloadedRoutes: hasPreloadedRoutes ? state.preloadedRoutes : [],
};
return originalGetStateForRouteNamesChange(safeState, options);
},
};
}
In PlatformNavigatorImpl:
+ const safeCreateRouter = React.useCallback(
+ (routerOptions: RouterOptions) => wrapRouterWithSafeRouteNamesChange((options?.createRouter ?? StackRouter)(routerOptions), displayName),
+ [displayName, options?.createRouter],
+ );
const {
navigation,
state: originalState,
descriptors,
describe,
NavigationContent,
} = useNavigationBuilder<
PlatformStackNavigationState<ParamListBase>,
RouterOptions,
StackActionHelpers<ParamListBase>,
NativeStackNavigationOptions,
NativeStackNavigationEventMap,
PlatformStackNavigationOptions
>(
- options?.createRouter ?? StackRouter,
+ safeCreateRouter,
{
id,
children,
screenOptions: {...defaultScreenOptions, ...screenOptions},
screenListeners,
initialRouteName,
sidebarScreen,
defaultCentralScreen,
parentRoute,
screenLayout,
},
convertToNativeNavigationOptions,
);
2. Defensive Upstream Patch in patches/react-navigation/
Add a patch to @react-navigation/routers (patches/react-navigation/@react-navigation+routers+7.6.4+002+safe-routes-filter-on-route-names-change.patch) to safeguard upstream execution:
--- a/node_modules/@react-navigation/routers/src/StackRouter.tsx
+++ b/node_modules/@react-navigation/routers/src/StackRouter.tsx
@@ -270,3 +270,3 @@ export function StackRouter(options: StackRouterOptions) {
- const routes = state.routes.filter((route) =>
+ const routes = (state?.routes ?? []).filter((route) =>
routeNames.includes(route.name)
);
3. Preserved State Sanity Guard in RightModalRouter
In src/libs/Navigation/AppNavigator/createRightModalNavigator/RightModalRouter.ts:
Ensure preservedState actually contains valid routes before using it as initial state:
getInitialState({routeNames, routeParamList, routeGetIdList}: RouterConfigOptions) {
const preservedState = getPreservedNavigatorState(options.parentRoute.key);
- return preservedState ?? stackRouter.getInitialState({routeNames, routeParamList, routeGetIdList});
+ if (preservedState && Array.isArray(preservedState.routes) && preservedState.routes.length > 0) {
+ return preservedState;
+ }
+ return stackRouter.getInitialState({routeNames, routeParamList, routeGetIdList});
},
What alternative solutions did you explore? (Optional)
- Patching
@react-navigation/routersonly: While the upstream patch stops the crash, it fails to recordLog.hmmmdiagnostics to identify the origin of incomplete states reachinguseNavigationBuilder. Implementing the decorator wrapper increatePlatformStackNavigatorComponentprovides both crash prevention and telemetry. - Guarding only inside
RightModalRouter: Only protectsRightModalNavigator, leaving other navigators (SearchFullscreenNavigator,SplitNavigator,OnboardingModalNavigator) vulnerable if they receive an incomplete preserved state.
Automated Test Scenarios
1. Unit Test in tests/unit/PlatformStackNavigationTest.ts
import wrapRouterWithSafeRouteNamesChange from '@libs/Navigation/PlatformStackNavigation/createPlatformStackNavigatorComponent/wrapRouterWithSafeRouteNamesChange';
import {StackRouter} from '@react-navigation/native';
import Log from '@libs/Log';
describe('wrapRouterWithSafeRouteNamesChange', () => {
it('does not throw when state.routes is undefined and returns a valid state', () => {
const hmmmSpy = jest.spyOn(Log, 'hmmm').mockImplementation(() => {});
const baseRouter = StackRouter({});
const wrappedRouter = wrapRouterWithSafeRouteNamesChange(baseRouter, 'TestNavigator');
const malformedState = {
key: 'stack-1',
index: 0,
routeNames: ['Home', 'SearchReport'],
routes: undefined as any,
stale: false,
type: 'stack',
};
let resultState: any;
expect(() => {
resultState = wrappedRouter.getStateForRouteNamesChange(malformedState, {
routeNames: ['Home', 'SearchReport'],
});
}).not.toThrow();
expect(Array.isArray(resultState.routes)).toBe(true);
expect(resultState.routes).toEqual([]);
expect(hmmmSpy).toHaveBeenCalledTimes(1);
expect(hmmmSpy).toHaveBeenCalledWith(
expect.stringContaining('[TestNavigator] getStateForRouteNamesChange received state with missing routes'),
expect.any(Object),
);
hmmmSpy.mockRestore();
});
it('preserves normal route filtering when state.routes is valid', () => {
const baseRouter = StackRouter({});
const wrappedRouter = wrapRouterWithSafeRouteNamesChange(baseRouter, 'TestNavigator');
const validState = {
key: 'stack-1',
index: 1,
routeNames: ['Home', 'SearchReport', 'Settings'],
routes: [
{key: 'home-1', name: 'Home'},
{key: 'search-1', name: 'SearchReport'},
{key: 'old-1', name: 'ObsoleteRoute'},
],
stale: false,
type: 'stack',
};
const resultState = wrappedRouter.getStateForRouteNamesChange(validState, {
routeNames: ['Home', 'SearchReport'],
});
expect(resultState.routes).toHaveLength(2);
expect(resultState.routes.map((r: any) => r.name)).toEqual(['Home', 'SearchReport']);
});
});
2. Unit Test in tests/unit/RightModalRouterTest.ts
it('falls back to stackRouter.getInitialState when preservedState has undefined routes', () => {
// Verify getInitialState returns fresh valid initial state instead of broken preservedState
});
Contributor Details
- Expensify Account Email: [email protected]
- Upwork Profile Link: https://www.upwork.com/freelancers/janithad
start checking the issue
Proposal
Please re-state the problem that we are trying to solve in this issue.
The iOS HybridApp crashes with Cannot read properties of undefined (reading 'filter') inside StackRouter.getStateForRouteNamesChange when a navigator (seen on SearchReport, inside the RHP) mounts.
What is the root cause of that problem?
Two things together:
-
The crashing line is new. In
@react-navigation/routers7.6.4,getStateForRouteNamesChangefilters bothstate.routesandstate.preloadedRoutes. ThepreloadedRoutesfilter was added upstream in July 2026 (react-navigation c0326785, "filter preloaded routes on route config changes"). 7.5.3 never read it. We picked it up in #98097 (core 7.16.1 → 7.21.12, routers 7.5.3 → 7.6.4), which reached production on 2026-08-20, and Sentry first saw this crash on 2026-08-24. So the property being read is almost certainlypreloadedRoutes, notroutes. -
We hand React Navigation a stack state that is missing
preloadedRoutes.RightModalRouter,SearchFullscreenRouter,WorkspaceRouterandSplitRouterrestore a "preserved" navigator state fromusePreserveNavigatorStateand return it as-is fromgetInitialState. That store is an untypedRecord<string, NavigationState>. It also receives tab-router states (which havepreloadedRouteKeys, notpreloadedRoutes) and partial snapshots fromrestoreTabNavigatorRoutes, and it is only cleared on logout. On HybridApp, AuthScreens can remount without a logout, so old snapshots survive. A restored state is markedstale: false, soStackRouter.getRehydratedStatereturns it untouched and nothing fills in the missingpreloadedRoutes. When the navigator's route names differ from the snapshot's,useNavigationBuildercallsgetStateForRouteNamesChangeon it, and it throws.
What changes do you think we should make in order to solve the problem?
- Validate preserved states before restoring them. In the four custom routers, only reuse a preserved state if it is a stack state with
routes,routeNamesandpreloadedRoutes. Otherwise discard it (with aLog.hmmmso we can see how often it happens) and fall back to the router's normal initial state. Run valid ones through the stack router'sgetRehydratedStatewithstale: true, sorouteNames,preloadedRoutesandindexare rebuilt for the current screen list. - Clear the preserved-state store when AuthScreens unmounts, not only on logout.
- As a safety net, add a small patch to
@react-navigation/routerssogetStateForRouteNamesChangetreats a missingroutes/preloadedRoutesas an empty list, and document it inpatches/react-navigation/details.md. - Unit tests: restoring a snapshot without
preloadedRoutes, a tab-router snapshot and a partial snapshot throughRightModalRoutershould each give a valid stack state, andgetStateForRouteNamesChangeon the result should not throw.
A null guard on its own (step 3) would stop the crash but leave the RHP/Search navigator running on a malformed state, so it would silently lose its stack instead of crashing. Steps 1 and 2 fix the source.
To confirm from Sentry: the top frame's column (StackRouter line 276 = preloadedRoutes, line 270 = routes) and the keys of the state object that was passed in.
What alternative solutions did you explore? (Optional)
Overriding getStateForRouteNamesChange only in our custom routers. It misses navigators that use the plain StackRouter (the PublicScreens root, modal stacks), and it still hides the malformed state.
📣 @tnclaudecode! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:
- Make sure you've read and understood the contributing guidelines.
- Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
- Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0163955a2ba22190aa
Proposal
Please re-state the problem that we are trying to solve in this issue.
The application experiences an unhandled Sentry crash: Cannot read properties of undefined (reading 'filter') inside React Navigation's StackRouter.getStateForRouteNamesChange when custom navigators (such as RightModalNavigator / SearchReport in the RHP, SearchFullscreenNavigator, SplitNavigator, or WorkspaceNavigator) mount or change route names.
What is the root cause of that problem?
In RightModalRouter.ts, SearchFullscreenRouter.ts, SplitRouter.ts, and WorkspaceRouter.ts:
- When custom navigators initialize, they restore snapshots using
getPreservedNavigatorState(options.parentRoute.key). - When a preserved state is found, it is currently returned raw directly from
getInitialState:const preservedState = getPreservedNavigatorState(options.parentRoute.key); return preservedState ?? stackRouter.getInitialState(configOptions); - Returning
preservedStatedirectly without validating or rehydrating it causes two critical failures:- If
preservedStatedoes not have a validroutesarray (e.g. partial snapshot, or state preserved across a route key change or tab switch),state.routesis undefined or malformed. - Preserved states carry
stale: false. When a navigator mounts with a different route set than the saved snapshot,useNavigationBuilderinvokesrouter.getStateForRouteNamesChange(state, {routeNames}). - Upstream
@react-navigation/routerscallsstate.routes.filter(...)andstate.preloadedRoutes ? state.preloadedRoutes.filter(...) : undefined. Because the raw preserved state was never validated and never passed throughstackRouter.getRehydratedState,state.routes(orpreloadedRoutes) is undefined, throwing:TypeError: Cannot read properties of undefined (reading 'filter').
- If
What changes do you think we should make in order to solve the problem?
In our custom routers:
src/libs/Navigation/AppNavigator/createRightModalNavigator/RightModalRouter.tssrc/libs/Navigation/AppNavigator/createSearchFullscreenNavigator/SearchFullscreenRouter.tssrc/libs/Navigation/AppNavigator/createSplitNavigator/SplitRouter.tssrc/libs/Navigation/AppNavigator/createWorkspaceNavigator/WorkspaceRouter.ts
Validate that preservedState has a non-empty routes array, and crucially pass it through stackRouter.getRehydratedState(preservedState, configOptions) before returning it. getRehydratedState is React Navigation's official contract for rehydrating state snapshots against the current route config, which safely synchronizes routeNames, populates all expected keys, and filters obsolete routes:
--- a/src/libs/Navigation/AppNavigator/createRightModalNavigator/RightModalRouter.ts
+++ b/src/libs/Navigation/AppNavigator/createRightModalNavigator/RightModalRouter.ts
@@ -11,9 +11,12 @@ function RightModalRouter(options: RightModalNavigatorRouterOptions) {
return {
...stackRouter,
- getInitialState({routeNames, routeParamList, routeGetIdList}: RouterConfigOptions) {
+ getInitialState(configOptions: RouterConfigOptions) {
const preservedState = getPreservedNavigatorState(options.parentRoute.key);
- return preservedState ?? stackRouter.getInitialState({routeNames, routeParamList, routeGetIdList});
+ if (preservedState && Array.isArray(preservedState.routes) && preservedState.routes.length > 0) {
+ return stackRouter.getRehydratedState(preservedState, configOptions);
+ }
+ return stackRouter.getInitialState(configOptions);
},
};
}
(Identical safeguard applied to SearchFullscreenRouter.ts, SplitRouter.ts, and WorkspaceRouter.ts).
Pre-coded and tested in branch: fix/103777-sentry-navigation-crash-filter (https://github.com/jloa-dev/App/tree/fix/103777-sentry-navigation-crash-filter).
What alternative solutions did you explore? (Optional)
Patching node_modules/@react-navigation/routers with an inline optional chaining null-check. While patching third-party packages is possible, fixing the custom router rehydration directly in application code is far cleaner, adheres to React Navigation router design, and completely avoids maintaining additional node_modules patches.
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
@eh2077 Huh... This is 4 days overdue. Who can take care of this?
still investigating the issue
@eh2077 Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!
sorry for the delay, catching up backlog
@mountiny @eh2077 this issue was created 2 weeks ago. Are we close to approving a proposal? If not, what's blocking us from getting this issue assigned? Don't hesitate to create a thread in #expensify-open-source to align faster in real time. Thanks!
@QichenZhu I'll be ooo, would you like to take over this?
Happy to, thanks!
@QichenZhu Eep! 4 days overdue now. Issues have feelings too...