Skip to content

Give the first page of a Search query a single owner - #101723

Merged
JS00001 merged 7 commits into
Expensify:mainfrom
callstack-internal:eliran/101642-dedupe-search-mount-fetch
Sep 25, 2026
Merged

JS00001 merged 7 commits into
Expensify:mainfrom
callstack-internal:eliran/101642-dedupe-search-mount-fetch

Conversation

@elirangoshen

@elirangoshen elirangoshen commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

Problem: one filter apply on Spend sends three identical Search commands. Same hash, same offset: 0, measured on a dev build:

1  POST /api/Search  +0ms    shouldSaveRecentSearch: true
2  POST /api/Search  +378ms  (key absent)
3  POST /api/Search  +781ms  shouldSaveRecentSearch: true

Two places fetch the same query, and they never overlap, so the duplicate check inside search() never catches them:

  • useSearchPageSetup.ts:99 fetches when the q param changes.
  • Search/index.tsx:477 fetches again when the component mounts.

While the first request runs, Search is not on screen. SearchPageWide.tsx:130-144 shows SearchLoadingSkeleton instead, and key={queryJSON.hash} rebuilds the subtree on every query change, so Search mounts only after the response arrives. By then search() has already removed the first request from its in-flight map, and nothing stops the second one.

The third follows from the second. Once it is running, isInitialSearchPending turns true, so the early return at useSearchPageSetup.ts:92-94 no longer applies and the page fetches again with the flag set. That lands on a running request with no flag, so needsSaveRecentSearchUpgrade queues one more.

Fix: give the first page one owner. useSearchPageSetup leaves a token when it fetches, and the mount reads that token once instead of fetching again. The token records whether totals were asked for, so a mount that needs totals the page did not request still fetches. Pagination, reconnect refresh, error retry and all-matching totals are unchanged, and needsSaveRecentSearchUpgrade stays as it is - that branch is what gets a user's own query to the backend with the flag.

One token, not a set: a new query replaces the old one, so a token left over from a query the user moved away from cannot skip a later refresh of it.

Automated tests: new tests/unit/Search/searchPageRequestedTokenTest.ts with 6 cases covering the token's lifetime, including the leftover-token and totals cases, plus a tests/ui/SearchPageTest.tsx case that asserts one first-page request per query change. That test was checked against the unfixed code and fails there (Expected: 1, Received: 2).

Fixed Issues

$ #101642
PROPOSAL:

Tests

  1. Open the browser network inspector on the Spend page.
  2. Apply a Merchant filter with a term you have not used this session.
  3. Verify exactly one Search command is sent for that query - one jsonQuery with the new hash at offset: 0, carrying shouldSaveRecentSearch: true.
  4. Scroll to load more and verify the next page is requested at offset: 50.
  5. Go offline, come back online on a query with no results, and verify the refresh still fires.
  • Verify that no errors appear in the JS console

Offline tests

Search is a READ command. Both call sites already return early when offline, and the new check only runs on a path that needs loaded data, so offline behavior is unchanged. Verified filtering while offline and on return to online.

QA Steps

No user-facing behavior change - this removes redundant network calls. Regression checks only:

  1. Apply a Merchant filter on Spend and verify results load normally.
  2. Scroll to load more and verify pagination works.
  3. Switch between Expenses and Reports tabs and back, verifying the list refreshes.
  4. Pay or approve from the Search page and verify the list refreshes.
  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari qa1-a-merchant-filter-entered search-with-fix qa1-b-results-loaded

Applying a filter fired three identical Search calls for one query: the
page-level fetch while the skeleton was up, the Search mount fetch once that
response landed, and the save-recent-search upgrade queued behind the second.
The in-flight check could not collapse them because the skeleton keeps Search
unmounted until the page's request has already finished.

The page now marks a one-shot token when it requests a first page, and the
mount effect reads it instead of repeating the request. The token carries the
totals intent, so a mount that needs totals the page did not request still
fires.
@elirangoshen
elirangoshen marked this pull request as ready for review September 21, 2026 12:10
@elirangoshen
elirangoshen requested review from a team as code owners September 21, 2026 12:10
@melvin-bot
melvin-bot Bot requested a review from marufsharifi September 21, 2026 12:10
@melvin-bot

melvin-bot Bot commented Sep 21, 2026

Copy link
Copy Markdown

@marufsharifi Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot
melvin-bot Bot requested review from a team and flaviadefaria and removed request for a team September 21, 2026 12:10
@marufsharifi

marufsharifi commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: HybridApp
Android: mWeb Chrome
iOS: HybridApp
iOS: mWeb Safari
MacOS: Chrome / Safari
fadsf.mov

@marufsharifi

Copy link
Copy Markdown
Contributor

@elirangoshen, could you please confirm this:

When the user returns to the same Spend search, it does not send a new Search request.

PR:

pr.mov

Main:

main.mov

@elirangoshen

Copy link
Copy Markdown
Contributor Author

@elirangoshen, could you please confirm this:

When the user returns to the same Spend search, it does not send a new Search request.

PR:

pr.mov
Main:

main.mov

I will look into it and update you

On a cached query Search is already on screen, so the page's flagged
request left a token nothing read, and it skipped the refresh on the
next return to the same query.
@elirangoshen

Copy link
Copy Markdown
Contributor Author

@elirangoshen, could you please confirm this:

When the user returns to the same Spend search, it does not send a new Search request.

PR:

pr.mov
Main:

main.mov

please try again

@codecov

codecov Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
src/components/Search/index.tsx 58.64% <100.00%> (+0.17%) ⬆️
src/hooks/useSearchPageSetup.ts 97.36% <100.00%> (+0.22%) ⬆️
src/libs/actions/Search.ts 58.87% <100.00%> (+0.54%) ⬆️
... and 13 files with indirect coverage changes

If the user leaves before the response lands, Search mounts only on
their return, and the page's token made it skip the refresh. Clear the
token when the page loses focus so the return refreshes as on main.
@marufsharifi

Copy link
Copy Markdown
Contributor

@elirangoshen, could you please merge the main. thanks.

@elirangoshen

Copy link
Copy Markdown
Contributor Author

@elirangoshen, could you please merge the main. thanks.

done

@marufsharifi

Copy link
Copy Markdown
Contributor

Thanks, i am still testing.

@marufsharifi marufsharifi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, just a few minor suggestions.

}

// The page already fetched this first page, and that request finished before Search mounts, so search() no longer sees it.
if (!shouldRefreshOnReconnect && searchRequestOffset === 0 && isDataLoaded && consumePageRequestedSearch(queryJSON.hash, shouldCalculateTotals)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1. No test for the !shouldRefreshOnReconnect guard

No test has a page token set while the app comes back online. If this guard were dropped, a reconnect refresh could be silently skipped, and every current test would still pass.

2. No test for the searchRequestOffset === 0 guard while a token is set

loads the next page after a request that was in flight… covers paging, but only with no token set. Nothing checks that a first-page token (a) doesn't block a later-page request and (b) isn't used up by one.

@elirangoshen elirangoshen Sep 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, I Addressed by adding tests

Comment thread src/components/Search/index.tsx Resolved
Comment thread src/hooks/useSearchPageSetup.ts Resolved
Comment thread src/hooks/useSearchPageSetup.ts Resolved
The claim's guards were invisible to the suite: deleting any of them left
every test green, which is what review pointed out.

Two mocks were hiding the hook side. One replaced useFocusEffect with a
bare jest.fn() so the callback never ran; the other ran the callback but
dropped the cleanup it returned, so the blur path never executed. The
token functions were stubbed and never asserted. The mock now keeps the
cleanup, and the stubs are spies.

Three hook tests: the page claims the first page when it owns the
request, does not claim it when data is already on screen, and drops the
claim on blur. The middle one needs cached data with a request still in
flight — with data simply loaded the effect returns earlier and never
reaches the guard, so a first version of that test passed with the guard
deleted.

Three component tests seed the claim directly, since only `search` is
mocked and the real token functions share module state with the
component. Removing `!shouldRefreshOnReconnect` or `searchRequestOffset
=== 0` now fails one each. The third covers the case review asked about:
a mount with no claim does not re-request a first page that just
finished loading. It pins that behaviour rather than the dependency
itself.
Drops the parts the code already says and keeps the two that explain
something non-obvious: why the fixture needs a request still in flight,
and why a later page does not consume the claim.
…e-search-mount-fetch

# Conflicts:
#	src/components/Search/index.tsx
#	src/hooks/useSearchPageSetup.ts

@marufsharifi marufsharifi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@melvin-bot
melvin-bot Bot requested a review from JS00001 September 25, 2026 09:24
@JS00001
JS00001 merged commit 3549627 into Expensify:main Sep 25, 2026
33 of 35 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

🚧 JS00001 has triggered a test Expensify/App build. You can view the workflow run here.

@OSBotify

Copy link
Copy Markdown
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/JS00001 in version: 9.4.94-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

@MelvinBot

Copy link
Copy Markdown
Contributor

No help site changes are needed for this PR, so I did not create a docs PR.

This PR only removes duplicate Search API requests when the Spend page loads a query. It adds no new features, settings, labels, or buttons, and it does not change what users see or do. Filtering, pagination, refresh, and recent searches work the same as before.

Files reviewed
  • src/components/Search/index.tsx, src/hooks/useSearchPageSetup.ts, src/libs/actions/Search.ts: add an internal token so the first page of results is fetched once.
  • tests/...: unit and UI tests only.
  • No changes to src/languages/* or any other user-facing copy.

view run

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/Julesssss in version: 9.4.94-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

Bundle Size Analysis (Sentry):

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants