[Due for payment 2026-11-25] [$175] [Sentry: APP-P0M] Null employee entry crashes Search custom-field selector
Sentry
https://expensify.sentry.io/issues/APP-P0M
Impact
- 3 users, 3 events since first seen on 2026-11-09 at 18:47 UTC.
- Platform: Android HybridApp.
- Release: 9.5.32.
- Route:
Search_Root. - Fatal, unhandled TypeError:
Cannot convert null value to object.
Top first-party frames
src/selectors/Policy.ts:369 — employee[key] inside customFieldKeys.map(...)
src/selectors/Policy.ts:368 — Object.entries(employeeList)
src/hooks/useOnyx.ts:102 — useOnyx
src/components/Search/index.tsx:267 — Search
Root cause
createMemberCustomFieldsSelector guards against a missing employee list but dereferences each employee without checking for null. A null entry therefore throws during Search rendering.
Member-removal updates use null employee entries. The selector does not tolerate this state; the exact operation triggering these events remains unconfirmed.
Suggested fix
Skip null employees before accessing their custom fields. Add regression coverage for an employee list containing both valid and null entries, ensuring valid members are preserved and Search does not crash.
Investigation
No matching issue found in Expensify/App or Expensify/Expensify when searching the Sentry ID, error text, and selector-specific terms.
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022120214848662666869
- Upwork Job ID: 2120214848662666869
- Last Price Increase: 2026-11-10
Issue Owner
Current Issue Owner: @mallenexpensify
Triggered auto assignment to Contributor-plus team member for initial proposal review - @aimane-chnaif (External)
Job added to Upwork: https://www.upwork.com/jobs/~022120214848662666869
Proposal
Please re-state the problem that we are trying to solve in this issue.
Search crashes with TypeError: Cannot convert null value to object when a policy's employeeList contains a null entry, because the member custom-fields selector reads fields off every employee without checking it exists.
What is the root cause of that problem?
In src/selectors/Policy.ts, createMemberCustomFieldsSelector only guards the list itself:
const employeeList = policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`]?.employeeList;
if (!employeeList) {
continue;
}
const customFieldsByLogin: Record<string, MemberCustomFields> = {};
for (const [login, employee] of Object.entries(employeeList)) {
customFieldsByLogin[login] = Object.fromEntries(customFieldKeys.map((key) => [key, employee[key]]));
}
employee[key] throws when employee is null. We do write null employee entries: removeMembers in src/libs/actions/Policy/Member.ts sets successMembersState[email] = null and merges it as employeeList, and clearAddMemberError merges employeeList: {[login]: null}. If one of those nulls is still present in the policy object when Search (src/components/Search/index.tsx, useMemo(() => createMemberCustomFieldsSelector(searchResultPolicyIDs), ...)) runs the selector, it crashes.
What changes do you think we should make in order to solve the problem?
In createMemberCustomFieldsSelector, skip falsy employees before reading custom fields:
for (const [login, employee] of Object.entries(employeeList)) {
if (!employee) {
continue;
}
customFieldsByLogin[login] = Object.fromEntries(customFieldKeys.map((key) => [key, employee[key]]));
}
A removed member then simply doesn't appear in the output, which matches how the rest of the app treats a null employee (as not a member).
What specific scenarios should we cover in automated tests?
In tests/unit/PolicySelectorTest.ts, under the existing describe('createMemberCustomFieldsSelector'), add a case where a policy's employeeList has one valid member and one null entry, and assert that the selector doesn't throw, returns the valid member's employeeUserID/employeePayrollID, and leaves out the null login.
What alternative solutions did you explore? (Optional)
Using optional chaining (employee?.[key]) instead. That stops the crash too, but it would return a row of undefined fields for a login that was removed, so skipping the entry is cleaner.
@MelvinBot can you make official proposal?
Proposal
Confidence: Medium — the code explains the crash, but the production trigger remains unconfirmed. This supports the defensive fix in the existing contributor proposal.
What is the root cause of that problem?
createMemberCustomFieldsSelector checks whether employeeList exists, but not whether each employee exists. If an entry is null, reading employee[key] throws during Search rendering.
Important distinction: null-valued member-removal updates do not prove the trigger. Ordinary Onyx merges remove those properties before notifying subscribers.
Code evidence and alternative explanations checked
- The release-family source contains the exact unsafe access at
src/selectors/Policy.ts:363–369, matching the reported stack. - Search subscribes using this selector at
src/components/Search/index.tsx:267–270. - A missing list is already guarded; missing custom-field properties on a valid employee return
undefined, rather than throwing. - Native Onyx merges clean nested nulls before broadcasting:
OnyxMerge/index.native.ts:16–30andOnyxUtils.ts:835–850. - Search can read snapshot rather than live policy data, so the offending data’s source remains unresolved:
src/hooks/useOnyx.ts:77–105.
Sentry/VictoriaLogs access was unavailable. No runtime reproduction or automated tests were run. Confirming provenance requires an affected event’s breadcrumbs and sanitized policy/snapshot data.
What changes do you think we should make in order to solve the problem?
Skip null or undefined employees before accessing their custom fields. Preserve valid members and omit nonexistent ones.
Change location and regression coverage
Add the guard inside the employee loop in src/selectors/Policy.ts:387–390.
Extend tests/unit/PolicySelectorTest.ts:203–249 to verify:
- A null entry followed by a valid employee does not throw.
- Both custom fields survive for the valid employee.
- The null login is omitted.
- An all-null list produces an empty member map.
What alternative solutions did you explore? (Optional)
Optional chaining prevents the exception but retains nonexistent members with undefined fields. Skipping those entries gives a cleaner result.
Next Steps for Contributor+ team:
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/106543) to create a draft PR.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.
@MelvinBot implement this
Proposal
What is the root cause of that problem?
In src/selectors/Policy.ts, createMemberCustomFieldsSelector extracts custom fields from all members across policies for Search (src/components/Search/index.tsx:267-270):
const employeeList = policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`]?.employeeList;
if (!employeeList) {
continue;
}
const customFieldsByLogin: Record<string, MemberCustomFields> = {};
for (const [login, employee] of Object.entries(employeeList)) {
customFieldsByLogin[login] = Object.fromEntries(customFieldKeys.map((key) => [key, employee[key]]));
}
customFieldsByPolicyID[policyID] = customFieldsByLogin;
While line 384 guards against employeeList itself being null or undefined (if (!employeeList) continue;), the loop iterates over Object.entries(employeeList) assuming every employee value is a valid object. When an entry is null, Object.entries(employeeList) yields [login, null]. Evaluating customFieldKeys.map((key) => [key, employee[key]]) then performs property access employee[key] on null, causing the fatal unhandled crash:
TypeError: Cannot convert null value to object (or TypeError: Cannot read properties of null).
Deep dive: Why null employee entries occur in production
- Member Deletions & Optimistic Updates: In Onyx, member removals explicitly write
nullvalues for employee keys to delete them from storage. For instance,removeMembersinsrc/libs/actions/Policy/Member.tssetssuccessMembersState[email] = nulland merges it intoemployeeList, andclearAddMemberErrormergesemployeeList: {[login]: null}. - Snapshot vs Live Merge Timing: While native Onyx merges clean nested nulls before broadcasting updates to live subscribers (
OnyxMerge/index.native.tsandOnyxUtils.ts),useOnyxinitial state reads from cache/disk snapshots before the live merge pipeline runs (src/hooks/useOnyx.ts:77–105). Additionally, backend API responses from commands likeOpenReport,ReconnectToReport, or bulk policy fetches can deliver policy objects containingnullmember keys. - Safe property vs Unsafe entry: Missing custom-field properties on a valid
PolicyEmployeeobject evaluate toundefinedsafely; the failure only triggers when the employee entry itself isnull.
What changes do you think we should make in order to solve the problem?
In src/selectors/Policy.ts, add an explicit guard if (!employee) continue; inside the employee iteration loop before accessing employee[key]:
const customFieldsByLogin: Record<string, MemberCustomFields> = {};
for (const [login, employee] of Object.entries(employeeList)) {
if (!employee) {
continue;
}
customFieldsByLogin[login] = Object.fromEntries(customFieldKeys.map((key) => [key, employee[key]]));
}
customFieldsByPolicyID[policyID] = customFieldsByLogin;
This guarantees that:
- Any
nullorundefinedemployee entry is skipped safely without throwing. - Only valid, active policy members are included in
customFieldsByLogin. - Deleted/removed members are excluded from the output rather than generating empty/undefined property maps.
Automated Tests Coverage
In tests/unit/PolicySelectorTest.ts under describe('createMemberCustomFieldsSelector'), extend the test suite to verify:
- Resilience against null/undefined member entries: When an
employeeListcontains both a valid member andnull/undefinedentries (simulating removed members), the selector does not throw, extracts the valid member'semployeeUserIDandemployeePayrollID, and omits the null/undefined entries. - All-null employee list: When all entries in
employeeListare null, the selector returns an empty object{}for that policy rather than throwing.
What alternative solutions did you explore? (Optional)
- Optional Chaining (
employee?.[key]): Usingemployee?.[key]prevents the exception, but produces an entrycustomFieldsByLogin[login] = { employeeUserID: undefined, employeePayrollID: undefined }. This pollutes the member map with deleted members, causes superfluous object churn and unnecessary re-renders for consumers subscribed tocreateMemberCustomFieldsSelector, and misrepresents deleted accounts as active members. Skipping the entry viaif (!employee) continue;is strictly cleaner and semantically correct. - Filtering entries before iteration (
Object.entries(employeeList).filter(...)): Creates an intermediate array and extra function allocation. The inlineif (!employee) continue;guard has zero overhead and matches existing idiomatic patterns in Expensify selectors (e.g.,src/selectors/Policy.ts:633).
Contributor details
Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374
Proposal
What is the root cause of that problem?
createMemberCustomFieldsSelector guards against a missing employeeList, but assumes every employee entry exists. A null entry causes employee[key] to throw, crashing Search.
Supporting evidence and verification limits
The unsafe access matches the reported stack at src/selectors/Policy.ts:363–369. Search uses this selector at src/components/Search/index.tsx:267–270.
The operation supplying the null remains unconfirmed. Member-removal payloads alone do not establish causation: ordinary Onyx merges clean nested nulls before notifying subscribers. No runtime reproduction or production-event inspection was completed.
What changes do you think we should make in order to solve the problem?
Skip null or undefined employee entries before reading their custom fields. Preserve the existing output for valid employees and omit nonexistent employees.
Implementation location and automated coverage
Add the guard inside the employee loop in src/selectors/Policy.ts:387–390.
Extend tests/unit/PolicySelectorTest.ts:203–249 to verify:
- Mixed valid, null, and undefined employees do not throw.
- Valid employees retain their
employeeUserIDandemployeePayrollID. - Null and undefined entries are omitted.
- An all-null list returns an empty member map for that policy.
What alternative solutions did you explore? (Optional)
Optional chaining prevents the crash but retains nonexistent employees with undefined custom fields. Skipping those entries avoids that misleading output.
Next Steps for Contributor+ team:
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/106543) to create a draft PR.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.
🤖 Web test steps verification results: ❌ fail
Verification was blocked by a blank web app and an unavailable session. This does not establish a regression.
| Step | Status |
|---|---|
Search opens without crashing and remains usableBlocked: the app returned no interactive nodes, so Search could not be opened. |
❌ |
Search handles null employees while retaining valid membersNot exercised in the browser because the app was unavailable. |
❌ |
Implemented and pushed: selector guard and regression tests.
- All 86 selector tests pass; the three new cases failed before the fix.
- Typecheck, lint, spelling, Storybook smoke check, and code review passed.
- Full Jest runs timed out without reported test failures. The required Prettier script is absent.
No draft PR created: full-suite and browser validation remain incomplete.
view run · no recording available
@MelvinBot implement your proposal
⏱️ Ran out of time before I could finish. This usually means the task was too complex or I got stuck exploring. Please try again with a more specific request or post in #melvinbot-ai.
Proposal
Please re-state the problem that we are trying to solve in this issue.
createMemberCustomFieldsSelector throws a fatal TypeError Cannot convert null value to object when dereferencing an employee entry that is null in employeeList during Search_Root rendering.
What is the root cause of that problem?
In src/selectors/Policy.ts inside createMemberCustomFieldsSelector (lines 388–390):
for (const [login, employee] of Object.entries(employeeList)) {
customFieldsByLogin[login] = Object.fromEntries(customFieldKeys.map((key) => [key, employee[key]]));
}
Member-removal updates in Onyx set deleted employee entries to null (e.g. employeeList[deletedMemberLogin] = null). While createMemberCustomFieldsSelector guards against a missing employeeList (if (!employeeList) continue;), it dereferences employee[key] without verifying that the individual employee entry is non-null.
What changes do you think we should make in order to solve the problem?
In src/selectors/Policy.ts:
Add a guard if (!employee) { continue; } at the start of the for (const [login, employee] of Object.entries(employeeList)) loop:
for (const [login, employee] of Object.entries(employeeList)) {
if (!employee) {
continue;
}
customFieldsByLogin[login] = Object.fromEntries(customFieldKeys.map((key) => [key, employee[key]]));
}
And add unit regression coverage in tests/unit/PolicySelectorTest.ts inside describe('createMemberCustomFieldsSelector', ...) verifying that an employeeList containing both valid and null employee entries is handled gracefully and valid members are retained:
it('handles null employee entries gracefully without throwing', () => {
const policies = {
[`${P}1`]: buildPolicy({
id: '1',
name: 'Workspace 1',
employeeList: {
'[email protected]': {
email: '[email protected]',
employeeUserID: 'U1',
employeePayrollID: 'P1',
},
'[email protected]': null as unknown as PolicyEmployee,
},
}),
};
expect(createMemberCustomFieldsSelector(['1'])(policies)).toEqual({
'1': {
'[email protected]': {employeeUserID: 'U1', employeePayrollID: 'P1'},
},
});
});
What alternative solutions did you explore? (Optional)
Optional chaining employee?.[key] or filtering with Object.values(employeeList).filter(Boolean), but an early if (!employee) continue; is the most idiomatic pattern across Expensify selectors, avoiding extra array allocations while preserving member logins.
📣 @almagas! 📣 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>
Proposal
Please re-state the problem that we are trying to solve in this issue.
When navigating to Search (Search_Root), the application crashes with an unhandled fatal error:
TypeError: Cannot convert null value to object (or Cannot read properties of null).
This occurs because createMemberCustomFieldsSelector in src/selectors/Policy.ts iterates over employeeList and accesses properties on employee without verifying whether the employee record itself is non-null.
What is the root cause of that problem?
In src/selectors/Policy.ts (lines 388–390):
const customFieldsByLogin: Record<string, MemberCustomFields> = {};
for (const [login, employee] of Object.entries(employeeList)) {
customFieldsByLogin[login] = Object.fromEntries(customFieldKeys.map((key) => [key, employee[key]]));
}
- While line 384 guards
employeeListitself (if (!employeeList) continue;),Object.entries(employeeList)yields pairs of[login, employee]. - In Onyx, member removals explicitly set
employeeList[email] = null(e.g.,removeMembersinsrc/libs/actions/Policy/Member.tssetssuccessMembersState[email] = null, andclearAddMemberErrorsetsemployeeList: {[login]: null}). - When
employeeisnull, evaluatingcustomFieldKeys.map((key) => [key, employee[key]])performs property lookup onnull, causing the unhandled TypeError.
What changes do you think we should make in order to solve the problem?
In src/selectors/Policy.ts, add a null check if (!employee) continue; at the start of the loop:
const customFieldsByLogin: Record<string, MemberCustomFields> = {};
for (const [login, employee] of Object.entries(employeeList)) {
if (!employee) {
continue;
}
customFieldsByLogin[login] = Object.fromEntries(customFieldKeys.map((key) => [key, employee[key]]));
}
This guarantees:
- Removed / null employees are safely skipped without throwing.
- Only valid members with defined custom fields are populated in
customFieldsByLogin. - Consumers subscribed to
createMemberCustomFieldsSelectorin Search receive clean data without ghost entries.
What specific scenarios should we cover in automated tests?
In tests/unit/PolicySelectorTest.ts under describe('createMemberCustomFieldsSelector'):
- Mixed valid and null members: Provide an
employeeListcontaining one valid member object and onenullmember. Verify that the selector does not throw, extracts the valid member's custom fields, and excludes thenullentry. - All null members: Provide an
employeeListwhere all entries arenull. Verify that the selector returns an empty dictionary{}for that policy without error.
What alternative solutions did you explore?
Using optional chaining (employee?.[key]). While this prevents the throw, it creates an entry with undefined values for a removed member, causing unnecessary downstream state churn. Skipping the falsy entry via if (!employee) continue; is the standard pattern used across other Policy selectors (e.g. line 361).
Contributor details Your Expensify account email: [email protected]
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0179cdc82689f205c7
Proposal
Please re-state the problem that we are trying to solve in this issue.
In Search custom-field filters on Android HybridApp, Sentry issue APP-P0M reports a fatal crash when selecting employee entries: TypeError: Cannot read property '...' of null.
What is the root cause of that problem?
In src/components/Search/SearchAdvancedFiltersCustomFields.tsx (or related employee picker filters in Search):
When mapping through workspace members / employees to populate the filter options, deactivated or deleted members can exist in Onyx policy employee lists as null or incomplete objects. The mapping function accesses employee properties (e.g. employee.displayName or employee.accountID) without null-safe optional chaining, throwing a TypeError.
What changes do you think we should make in order to solve the problem?
- In
src/components/Search/SearchAdvancedFiltersCustomFields.tsx:- Add defensive null guards and filter out
null/undefinedentries:employees.filter((e): e is Employee => !!e && !!e.accountID). - Use optional chaining (
employee?.displayName,employee?.email) when generating filter labels.
- Add defensive null guards and filter out
What alternative solutions did you explore? (Optional)
Cleaning up null entries on the server, but client-side defensive guards are mandatory in Expensify codebase to prevent crashes from stale cache.
Automated Tests
Add unit test in tests/unit/SearchAdvancedFiltersCustomFieldsTest.tsx:
- Verify filter renders safely and does not crash when employee list contains
nullor partial entries.
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
@aimane-chnaif how is this looking?
⏱️ Ran out of time before I could finish. This usually means the task was too complex or I got stuck exploring. Please try again with a more specific request or post in #melvinbot-ai.
Melvin's stuck on implementation
@aimane-chnaif can you try again with a bit updated prompt
Proposal
Please re-state the problem that we are trying to solve in this issue.
Navigating to Search (Search_Root) throws an unhandled TypeError: Cannot convert null value to object when any workspace policy in Onyx has a null employee entry inside policy.employeeList.
What is the root cause of that problem?
In src/selectors/Policy.ts:377-395, createMemberCustomFieldsSelector iterates over Object.entries(employeeList) and immediately dereferences employee[key]:
const createMemberCustomFieldsSelector = (policyIDs: string[]) => {
const customFieldKeys = Object.values(CONST.CUSTOM_FIELD_KEYS);
return (policies: OnyxCollection<Policy>): MemberCustomFieldsByPolicyID => {
const customFieldsByPolicyID: MemberCustomFieldsByPolicyID = {};
for (const policyID of policyIDs) {
const employeeList = policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`]?.employeeList;
if (!employeeList) {
continue;
}
const customFieldsByLogin: Record<string, MemberCustomFields> = {};
for (const [login, employee] of Object.entries(employeeList)) {
customFieldsByLogin[login] = Object.fromEntries(customFieldKeys.map((key) => [key, employee[key]]));
}
customFieldsByPolicyID[policyID] = customFieldsByLogin;
}
return customFieldsByPolicyID;
};
};
Although PolicyEmployeeList is typed as Record<string, PolicyEmployee>, workspace member removal actions and backend delta updates write null to employeeList[email] (for example in removeMembers / failure & success Onyx merges in src/libs/actions/Policy/Member.ts), and nested null keys inside an Onyx object can remain present in memory or storage until pruned. When Search (src/components/Search/index.tsx:267) runs useOnyx(ONYXKEYS.COLLECTION.POLICY, {selector: createMemberCustomFieldsSelector(policyIDs)}), employee is null for that entry and employee[key] throws TypeError: Cannot convert null value to object.
What changes do you think we should make in order to solve the problem?
- Guard against nullish
employeeentries increateMemberCustomFieldsSelector(src/selectors/Policy.ts:388-391): Skip any entry where!employeebefore readingemployee[key]:for (const [login, employee] of Object.entries(employeeList)) { if (!employee) { continue; } customFieldsByLogin[login] = Object.fromEntries(customFieldKeys.map((key) => [key, employee[key]])); } - Add unit tests for
createMemberCustomFieldsSelector(tests/unit/PolicySelectorTest.ts): Verify that whenemployeeListcontains both validPolicyEmployeerecords andnull/undefinedentries (cast viaas unknown as PolicyEmployee),createMemberCustomFieldsSelectordoes not throw, omits the null entries, and preserves the custom fields (customField1,customField2) of all valid members.
What alternative solutions did you explore?
Using optional chaining (employee?.[key]) while still inserting login into customFieldsByLogin was considered, but a null employee entry represents a removed member rather than an active member with empty custom fields, so skipping !employee with continue is cleaner and avoids polluting customFieldsByLogin with deleted logins.