From 7d66618b5bd33a1edfcaacaccb234f522ac6f7f5 Mon Sep 17 00:00:00 2001 From: Hubert Sosinski Date: Wed, 18 Nov 2026 14:11:58 +0100 Subject: [PATCH 1/3] Add useOnyxState wrapper with Search snapshot support --- __mocks__/react-native-onyx.ts | 4 +- .../philosophies/ONYX-DATA-MANAGEMENT.md | 5 + oxlint.config.mts | 6 + package-lock.json | 4 +- package.json | 2 +- src/hooks/useOnyx.ts | 1 + src/hooks/useOnyxState.ts | 103 ++++++ .../hooks/useOnyxStateSearchSnapshot.test.tsx | 341 ++++++++++++++++++ 8 files changed, 461 insertions(+), 5 deletions(-) create mode 100644 src/hooks/useOnyxState.ts create mode 100644 tests/unit/hooks/useOnyxStateSearchSnapshot.test.tsx diff --git a/__mocks__/react-native-onyx.ts b/__mocks__/react-native-onyx.ts index 6db22ac1b627..f5b09f2949da 100644 --- a/__mocks__/react-native-onyx.ts +++ b/__mocks__/react-native-onyx.ts @@ -5,7 +5,7 @@ import type {ConnectOptions, OnyxKey} from 'react-native-onyx'; // eslint-disable-next-line no-restricted-imports -import Onyx, {useOnyx} from 'react-native-onyx'; +import Onyx, {useOnyx, useOnyxState} from 'react-native-onyx'; let connectCallbackDelay = 0; function addDelayToConnectCallback(delay: number) { @@ -41,4 +41,4 @@ const reactNativeOnyxMock: ReactNativeOnyxMock = { export default reactNativeOnyxMock; -export {useOnyx}; +export {useOnyx, useOnyxState}; diff --git a/contributingGuides/philosophies/ONYX-DATA-MANAGEMENT.md b/contributingGuides/philosophies/ONYX-DATA-MANAGEMENT.md index 79a6944862a4..23615db7908e 100644 --- a/contributingGuides/philosophies/ONYX-DATA-MANAGEMENT.md +++ b/contributingGuides/philosophies/ONYX-DATA-MANAGEMENT.md @@ -71,6 +71,11 @@ It reads the cache once and never subscribes, so the value it returns MUST NOT r Read live data only when the read replaces a subscription that never went through the `useOnyx` redirection, such as a module-level `Onyx.connect()` used only from handlers. In that case, disable `rulesdir/no-onyx-get-snapshot-key` on that line with a reason after `--`. For `Onyx.multiGet()`, disable it on the line of the call, which covers every key in the list. For example: `// eslint-disable-next-line rulesdir/no-onyx-get-snapshot-key -- replaces a module-level Onyx.connect used only by handlers, never read a snapshot`. Disable one line at a time, always with a reason. Reviewers judge the reason. A read of the Concierge chat always needs the live report, in any Search scope. `Onyx.get()` may read `${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}` without a disable when `conciergeReportID` is a same-file `const` bound to a read of `ONYXKEYS.CONCIERGE_REPORT_ID`. +### - `useOnyxState` MUST be imported from `@hooks/useOnyxState` +`@hooks/useOnyxState` wraps the Onyx hook the same way `@hooks/useOnyx` wraps `useOnyx`. Inside a `SearchScopeProvider`, a selector that reads a key in `CONST.SEARCH.SNAPSHOT_ONYX_KEYS` gets the value from the current Search snapshot, and the hook subscribes to that snapshot instead of the live key. Every other key is read live. The Onyx hook always reads live keys, so importing it directly makes a component show live data on Search. Lint bans that import. + +A selector that keeps a module-level cache MUST key it by the value it read, for example a `WeakMap` from the collection to the result. The same selector can run with snapshot data in one component and live data in another, so a cache that holds only the last input is evicted on every switch between the two. To compare with the previous input, read it from `previousState`, which goes through the same redirection. + ### - Reads MUST come before a merge, mergeCollection, setCollection, update or clear in the same tick, or after it is awaited `Onyx.get()` reads the cache when it is called. `Onyx.set()` and `Onyx.multiSet()` update the cache before they return, but `Onyx.merge()`, `Onyx.mergeCollection()`, `Onyx.setCollection()`, `Onyx.clear()` and every `Onyx.update()` operation, including SET, land after at least one microtask. A read queued behind one of those returns the old value. A derived key (`ONYXKEYS.DERIVED.*`) lags its sources, so read it only before writing them. diff --git a/oxlint.config.mts b/oxlint.config.mts index 303c7d209c46..8742b5817b28 100644 --- a/oxlint.config.mts +++ b/oxlint.config.mts @@ -67,6 +67,12 @@ const restrictedImportPaths = [ {name: 'lodash/isEqual', message: "Please use 'deepEqual' from 'fast-equals' instead."}, {name: 'lodash', importNames: ['isEqual'], message: "Please use 'deepEqual' from 'fast-equals' instead."}, {name: 'react-native-onyx', importNames: ['useOnyx'], message: "Please use '@hooks/useOnyx' instead."}, + {name: 'react-native-onyx', importNames: ['useOnyxState'], message: "Please use '@hooks/useOnyxState' instead."}, + { + name: 'react-native-onyx/dist/useOnyxState', + message: "Please use '@hooks/useOnyxState' instead. Type-only imports are still allowed.", + allowTypeImports: true, + }, {name: '@src/utils/findNodeHandle', message: "Do not use 'findNodeHandle' as it is no longer supported on web."}, ]; diff --git a/package-lock.json b/package-lock.json index 410fabc5181c..2600debcf600 100644 --- a/package-lock.json +++ b/package-lock.json @@ -129,7 +129,7 @@ "react-native-nitro-image": "0.15.2", "react-native-nitro-modules": "0.37.1", "react-native-nitro-sqlite": "10.2.0", - "react-native-onyx": "git+https://github.com/Expensify/react-native-onyx.git#b63721334b5a41f527d78bd1c12e2aae7241c5c7", + "react-native-onyx": "git+https://github.com/callstack-internal/react-native-onyx.git#9b4cc4a7f6a070f5941196dcd45dcb2534f6592f", "react-native-pager-view": "9.0.4", "react-native-pdf": "7.0.2", "react-native-permissions": "^5.6.3", @@ -38527,7 +38527,7 @@ }, "node_modules/react-native-onyx": { "version": "3.0.155", - "resolved": "git+ssh://git@github.com/Expensify/react-native-onyx.git#b63721334b5a41f527d78bd1c12e2aae7241c5c7", + "resolved": "git+ssh://git@github.com/callstack-internal/react-native-onyx.git#9b4cc4a7f6a070f5941196dcd45dcb2534f6592f", "integrity": "sha512-6cUo+I+K/Ady1sEvXBVn4tCpAVNNeLsMfeN7Z+m7IZevB+aII65EzUvklqAk54u76/1LEYpPgXHxFDBd0tB23A==", "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index 4f5bb36eadb1..7d3bc17f687c 100644 --- a/package.json +++ b/package.json @@ -205,7 +205,7 @@ "react-native-nitro-image": "0.15.2", "react-native-nitro-modules": "0.37.1", "react-native-nitro-sqlite": "10.2.0", - "react-native-onyx": "git+https://github.com/Expensify/react-native-onyx.git#b63721334b5a41f527d78bd1c12e2aae7241c5c7", + "react-native-onyx": "git+https://github.com/callstack-internal/react-native-onyx.git#9b4cc4a7f6a070f5941196dcd45dcb2534f6592f", "react-native-pager-view": "9.0.4", "react-native-pdf": "7.0.2", "react-native-permissions": "^5.6.3", diff --git a/src/hooks/useOnyx.ts b/src/hooks/useOnyx.ts index b078cc80726b..0bb479f10500 100644 --- a/src/hooks/useOnyx.ts +++ b/src/hooks/useOnyx.ts @@ -108,3 +108,4 @@ const useOnyx: UseOnyxWithoutSnapshots = , Map>(); + +/** + * Reads a key out of a Search snapshot. A collection root returns the same object for as long as the snapshot's `data` stays + * the same, because selectors compare their inputs by reference and a collection rebuilt on every read would always look changed. + */ +function getSnapshotKeyData(snapshot: SearchResults | undefined, key: OnyxKey): unknown { + const data = snapshot?.data; + if (!snapshot || !data) { + return undefined; + } + if (!key.endsWith('_')) { + return getKeyData(snapshot, key); + } + + let collections = collectionsBySnapshotData.get(data); + if (!collections) { + collections = new Map(); + collectionsBySnapshotData.set(data, collections); + } + if (!collections.has(key)) { + collections.set(key, getKeyData(snapshot, key)); + } + return collections.get(key); +} + +/** + * Wraps a state view so that snapshot keys are answered from the Search snapshot. The read of the snapshot goes through + * `state`, so `useOnyxState` subscribes to the snapshot instead of the live key. + */ +function createSnapshotStateView(state: OnyxStateView, snapshotKey: SnapshotKey): OnyxStateView { + const read = (key: string | symbol): unknown => { + if (typeof key !== 'string') { + return undefined; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- a state view takes any string and returns undefined for a key Onyx does not hold + const onyxKey = key as OnyxKey; + if (!isSnapshotCompatibleKey(onyxKey, CONST.SEARCH.SNAPSHOT_ONYX_KEYS)) { + return state[onyxKey]; + } + return getSnapshotKeyData(state[snapshotKey], onyxKey); + }; + + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- the Proxy answers every key, which the type of its empty target cannot express + return new Proxy( + {}, + { + get: (_target, key) => read(key), + has: (_target, key) => read(key) !== undefined, + set: () => false, + deleteProperty: () => false, + }, + ) as OnyxStateView; +} + +function useSearchSnapshotKey(): SnapshotKey | undefined { + const isOnSearch = useIsOnSearch(); + if (!isOnSearch) { + return undefined; + } + + const {currentSearchHash} = use(SearchQueryContext); + const {shouldUseLiveData} = use(SearchResultsContext); + if (!currentSearchHash || shouldUseLiveData) { + return undefined; + } + return `${ONYXKEYS.COLLECTION.SNAPSHOT}${currentSearchHash}`; +} + +function useOnyxState(selector: UseOnyxStateSelector, options?: UseOnyxStateOptions): T { + const snapshotKey = useSearchSnapshotKey(); + + const snapshotAwareSelector: UseOnyxStateSelector = snapshotKey + ? (state, previousState) => selector(createSnapshotStateView(state, snapshotKey), previousState && createSnapshotStateView(previousState, snapshotKey)) + : selector; + + return useOnyxStateWithoutSnapshots(snapshotAwareSelector, options); +} + +export default useOnyxState; diff --git a/tests/unit/hooks/useOnyxStateSearchSnapshot.test.tsx b/tests/unit/hooks/useOnyxStateSearchSnapshot.test.tsx new file mode 100644 index 000000000000..2ddf3a6de85d --- /dev/null +++ b/tests/unit/hooks/useOnyxStateSearchSnapshot.test.tsx @@ -0,0 +1,341 @@ +import {act, render, renderHook} from '@testing-library/react-native'; + +import {SearchQueryContext, SearchResultsContext} from '@components/Search/SearchContextDefinitions'; +import {SearchScopeProvider} from '@components/Search/SearchScopeProvider'; + +import useOnyxState from '@hooks/useOnyxState'; + +import ONYXKEYS from '@src/ONYXKEYS'; +import type {Report} from '@src/types/onyx'; +import type ChildrenProps from '@src/types/utils/ChildrenProps'; + +import type {OnyxStateView} from 'react-native-onyx'; + +import React, {use, useMemo} from 'react'; +import Onyx from 'react-native-onyx'; + +import waitForBatchedUpdatesWithAct from '../../utils/waitForBatchedUpdatesWithAct'; + +const SEARCH_HASH = 42; +const OTHER_SEARCH_HASH = 43; +const SNAPSHOT_KEY = `${ONYXKEYS.COLLECTION.SNAPSHOT}${SEARCH_HASH}` as const; +const OTHER_SNAPSHOT_KEY = `${ONYXKEYS.COLLECTION.SNAPSHOT}${OTHER_SEARCH_HASH}` as const; +const REPORT_KEY = `${ONYXKEYS.COLLECTION.REPORT}1` as const; +const REPORT_MISSING_FROM_SNAPSHOT_KEY = `${ONYXKEYS.COLLECTION.REPORT}2` as const; +const POLICY_KEY = `${ONYXKEYS.COLLECTION.POLICY}A` as const; + +const LIVE_REPORT: Report = {reportID: '1', reportName: 'Live report'}; +const SNAPSHOT_REPORT: Report = {reportID: '1', reportName: 'Snapshot report'}; +const OTHER_SNAPSHOT_REPORT: Report = {reportID: '1', reportName: 'Other snapshot report'}; +const REPORT_MISSING_FROM_SNAPSHOT: Report = {reportID: '2', reportName: 'Live only report'}; +const LIVE_SESSION_EMAIL = 'live@expensify.com'; + +type SearchScreenProps = ChildrenProps & { + isOnSearch?: boolean; + shouldUseLiveData?: boolean; + searchHash?: number; +}; + +function SearchScreen({children, isOnSearch = true, shouldUseLiveData = false, searchHash = SEARCH_HASH}: SearchScreenProps) { + const queryContext = use(SearchQueryContext); + const resultsContext = use(SearchResultsContext); + const queryContextWithHash = useMemo(() => ({...queryContext, currentSearchHash: searchHash}), [queryContext, searchHash]); + const resultsContextWithLiveData = useMemo(() => ({...resultsContext, shouldUseLiveData}), [resultsContext, shouldUseLiveData]); + + return ( + + + {children} + + + ); +} + +function SearchScreenWithLiveData({children}: ChildrenProps) { + return {children}; +} + +function SearchScreenOutsideSearchScope({children}: ChildrenProps) { + return {children}; +} + +function selectReport(state: OnyxStateView) { + return state[REPORT_KEY]; +} + +function selectReports(state: OnyxStateView) { + return state[ONYXKEYS.COLLECTION.REPORT]; +} + +function selectReportMissingFromSnapshot(state: OnyxStateView) { + return state[REPORT_MISSING_FROM_SNAPSHOT_KEY]; +} + +function selectSessionEmail(state: OnyxStateView) { + return state[ONYXKEYS.SESSION]?.email; +} + +function selectSnapshotReport(state: OnyxStateView) { + return state[SNAPSHOT_KEY]?.data?.[REPORT_KEY]; +} + +function selectReportNameAndSessionEmail(state: OnyxStateView) { + return {reportName: state[REPORT_KEY]?.reportName, email: state[ONYXKEYS.SESSION]?.email}; +} + +function selectReportsAndSessionEmail(state: OnyxStateView) { + return {reports: state[ONYXKEYS.COLLECTION.REPORT], email: state[ONYXKEYS.SESSION]?.email}; +} + +function selectReportNameWithPrevious(state: OnyxStateView, previousState: OnyxStateView | undefined) { + return {reportName: state[REPORT_KEY]?.reportName, previousReportName: previousState?.[REPORT_KEY]?.reportName}; +} + +function selectHasReportMissingFromSnapshot(state: OnyxStateView) { + return REPORT_MISSING_FROM_SNAPSHOT_KEY in state; +} + +async function renderSelector(selector: (state: OnyxStateView, previousState: OnyxStateView | undefined) => T, wrapper?: React.ComponentType) { + const rendered = renderHook(() => useOnyxState(selector), {wrapper}); + await waitForBatchedUpdatesWithAct(); + return rendered; +} + +beforeAll(() => Onyx.init({keys: ONYXKEYS})); + +describe('useOnyxState Search snapshot redirect', () => { + beforeEach(async () => { + await Onyx.clear(); + await Onyx.multiSet({ + [REPORT_KEY]: LIVE_REPORT, + [REPORT_MISSING_FROM_SNAPSHOT_KEY]: REPORT_MISSING_FROM_SNAPSHOT, + [ONYXKEYS.SESSION]: {email: LIVE_SESSION_EMAIL}, + }); + await Onyx.merge(SNAPSHOT_KEY, { + data: { + [REPORT_KEY]: SNAPSHOT_REPORT, + [POLICY_KEY]: {id: 'A', name: 'Snapshot policy'}, + }, + }); + await Onyx.merge(OTHER_SNAPSHOT_KEY, {data: {[REPORT_KEY]: OTHER_SNAPSHOT_REPORT}}); + await waitForBatchedUpdatesWithAct(); + }); + + it('should read live data outside Search', async () => { + // Given a report whose live and snapshot copies differ + // When a selector reads it outside any Search scope + const {result} = await renderSelector(selectReport); + + // Then the live copy is returned because only Search screens use snapshots + expect(result.current).toEqual(LIVE_REPORT); + }); + + it('should read the snapshot copy of a member inside Search', async () => { + // Given a report whose live and snapshot copies differ + // When a selector reads it on a Search screen + const {result} = await renderSelector(selectReport, SearchScreen); + + // Then the snapshot copy is returned so the value matches what useOnyx returns on Search + expect(result.current).toEqual(SNAPSHOT_REPORT); + }); + + it('should return only the snapshot members of a collection inside Search', async () => { + // Given two live reports and a snapshot that holds only one of them next to a policy + // When a selector reads the report collection on a Search screen + const {result} = await renderSelector(selectReports, SearchScreen); + + // Then only the snapshot report comes back so the collection matches the search results + expect(result.current).toEqual({[REPORT_KEY]: SNAPSHOT_REPORT}); + }); + + it('should return nothing inside Search for a report the snapshot does not hold', async () => { + // Given a report that exists live but is missing from the snapshot + // When a selector reads it on a Search screen + const {result} = await renderSelector(selectReportMissingFromSnapshot, SearchScreen); + + // Then nothing is returned because Search never falls back to live data + expect(result.current).toBeUndefined(); + }); + + it('should read live data inside Search when live data is requested', async () => { + // Given a Search screen that asks for live data + // When a selector reads a report on that screen + const {result} = await renderSelector(selectReport, SearchScreenWithLiveData); + + // Then the live copy is returned because the screen opted out of snapshots + expect(result.current).toEqual(LIVE_REPORT); + }); + + it('should read live data when the Search scope is turned off', async () => { + // Given a Search screen with a search hash but a scope marked as not on Search + // When a selector reads a report on that screen + const {result} = await renderSelector(selectReport, SearchScreenOutsideSearchScope); + + // Then the live copy is returned because the scope decides whether snapshots apply + expect(result.current).toEqual(LIVE_REPORT); + }); + + it('should read live data inside Search for keys that snapshots do not copy', async () => { + // Given a live session, which snapshots never hold + // When a selector reads it on a Search screen + const {result} = await renderSelector(selectSessionEmail, SearchScreen); + + // Then the live value is returned because only snapshot keys are redirected + expect(result.current).toBe(LIVE_SESSION_EMAIL); + }); + + it('should never redirect a snapshot key inside Search', async () => { + // Given a snapshot that holds a report + // When a selector reads the snapshot key itself on a Search screen + const {result} = await renderSelector(selectSnapshotReport, SearchScreen); + + // Then the snapshot is read as is so Search can read its own results + expect(result.current).toEqual(SNAPSHOT_REPORT); + }); + + it('should return nothing inside a Search scope that has no search hash', async () => { + // Given a Search scope without a search query, so the default search hash applies + // When a selector reads a report that exists live in that scope + const {result} = await renderSelector(selectReport, SearchScopeProvider); + + // Then nothing is returned because the default hash has no snapshot, the same as useOnyx + expect(result.current).toBeUndefined(); + }); + + it('should redirect only the snapshot keys of a selector that reads several keys', async () => { + // Given a selector that reads a report, which snapshots copy, and the session, which they do not + // When it runs on a Search screen + const {result} = await renderSelector(selectReportNameAndSessionEmail, SearchScreen); + + // Then each key is resolved on its own, so the report comes from the snapshot and the session stays live + expect(result.current).toEqual({reportName: SNAPSHOT_REPORT.reportName, email: LIVE_SESSION_EMAIL}); + }); + + it('should answer the in operator from the snapshot inside Search', async () => { + // Given a report that exists live but is missing from the snapshot + // When selectors check for it with the in operator inside and outside Search + const {result: searchResult} = await renderSelector(selectHasReportMissingFromSnapshot, SearchScreen); + const {result: liveResult} = await renderSelector(selectHasReportMissingFromSnapshot); + + // Then the check agrees with what a read returns in each place + expect(searchResult.current).toBe(false); + expect(liveResult.current).toBe(true); + }); + + it('should return the same collection while the snapshot data is unchanged', async () => { + // Given a selector on a Search screen that returns the report collection next to the session email + const {result} = await renderSelector(selectReportsAndSessionEmail, SearchScreen); + const reportsBeforeSessionChange = result.current.reports; + + // When the session changes, which runs the selector again without touching the snapshot + await act(() => Onyx.merge(ONYXKEYS.SESSION, {email: 'other@expensify.com'})); + await waitForBatchedUpdatesWithAct(); + + // Then the collection is the same object, because selectors compare their inputs by reference to skip work + expect(result.current.email).toBe('other@expensify.com'); + expect(result.current.reports).toBe(reportsBeforeSessionChange); + }); + + it('should not run the selector again when the component re-renders with unchanged data', async () => { + // Given a selector rendered on a Search screen + const selector = jest.fn(selectReport); + const {rerender} = await renderSelector(selector, SearchScreen); + const runsAfterMount = selector.mock.calls.length; + + // When the component re-renders without any Onyx change + rerender({}); + await waitForBatchedUpdatesWithAct(); + + // Then the selector is not run again, because the redirect must not defeat the skip that useOnyxState does for unchanged inputs + expect(selector.mock.calls.length).toBe(runsAfterMount); + }); +}); + +describe('useOnyxState Search snapshot updates', () => { + beforeEach(async () => { + await Onyx.clear(); + await Onyx.set(REPORT_KEY, LIVE_REPORT); + await Onyx.merge(SNAPSHOT_KEY, {data: {[REPORT_KEY]: SNAPSHOT_REPORT}}); + await Onyx.merge(OTHER_SNAPSHOT_KEY, {data: {[REPORT_KEY]: OTHER_SNAPSHOT_REPORT}}); + await waitForBatchedUpdatesWithAct(); + }); + + it('should not run the selector inside Search after a plain merge to live data', async () => { + // Given a selector that reads a report on a Search screen + const selector = jest.fn(selectReport); + const {result} = await renderSelector(selector, SearchScreen); + const runsAfterMount = selector.mock.calls.length; + + // When the live report is changed with a plain merge, which does not touch the snapshot + await act(() => Onyx.merge(REPORT_KEY, {reportName: 'Merged report'})); + await waitForBatchedUpdatesWithAct(); + + // Then the selector does not run and the snapshot copy stays, because inside Search the hook subscribes to the snapshot only + expect(selector.mock.calls.length).toBe(runsAfterMount); + expect(result.current).toEqual(SNAPSHOT_REPORT); + }); + + it('should return the new value inside Search after an update that reaches the snapshot', async () => { + // Given a selector that reads a report on a Search screen + const {result} = await renderSelector(selectReport, SearchScreen); + + // When an update changes the report name, which Onyx also applies to the snapshot + await act(() => Onyx.update([{onyxMethod: Onyx.METHOD.MERGE, key: REPORT_KEY, value: {reportName: 'Updated report'}}])); + await waitForBatchedUpdatesWithAct(); + + // Then the new name is returned because the hook follows the snapshot + expect(result.current).toEqual({...SNAPSHOT_REPORT, reportName: 'Updated report'}); + }); + + it('should give previousState the previous snapshot copy inside Search', async () => { + // Given a selector on a Search screen that reads the report name from both state and previousState + const {result} = await renderSelector(selectReportNameWithPrevious, SearchScreen); + + // When an update changes the report name in the snapshot + await act(() => Onyx.update([{onyxMethod: Onyx.METHOD.MERGE, key: REPORT_KEY, value: {reportName: 'Updated report'}}])); + await waitForBatchedUpdatesWithAct(); + + // Then previousState holds the snapshot copy from before the update, so incremental selectors compare snapshot data with snapshot data + expect(result.current).toEqual({reportName: 'Updated report', previousReportName: SNAPSHOT_REPORT.reportName}); + }); + + it('should read the new snapshot with an empty previousState after the search hash changes', async () => { + // Given a selector that reads state and previousState on a Search screen showing the first search + const values: Array> = []; + function Reader() { + values.push(useOnyxState(selectReportNameWithPrevious)); + return null; + } + const {rerender} = render( + + + , + ); + await waitForBatchedUpdatesWithAct(); + + // When the screen switches to a second search that has its own snapshot + rerender( + + + , + ); + await waitForBatchedUpdatesWithAct(); + + // Then the report comes from the second snapshot, and previousState has nothing for it because the last run read the first snapshot + expect(values.at(-1)).toEqual({reportName: OTHER_SNAPSHOT_REPORT.reportName, previousReportName: undefined}); + }); + + it('should keep a consumer inside Search apart from one outside it', async () => { + // Given the same selector rendered once on a Search screen and once outside any Search scope + const {result: searchResult} = await renderSelector(selectReport, SearchScreen); + const {result: liveResult} = await renderSelector(selectReport); + + // When the live report is changed with a plain merge + await act(() => Onyx.merge(REPORT_KEY, {reportName: 'Merged report'})); + await waitForBatchedUpdatesWithAct(); + + // Then only the outside consumer sees the change, because each one reads from its own source + expect(liveResult.current).toEqual({...LIVE_REPORT, reportName: 'Merged report'}); + expect(searchResult.current).toEqual(SNAPSHOT_REPORT); + }); +}); From 9a0c3c68a4f4cba12ded5af5af7c08cc134fff2b Mon Sep 17 00:00:00 2001 From: Hubert Sosinski Date: Wed, 18 Nov 2026 14:49:45 +0100 Subject: [PATCH 2/3] Add live data option to useOnyxState wrapper --- .../philosophies/ONYX-DATA-MANAGEMENT.md | 2 +- src/hooks/useOnyxState.ts | 24 +++++++++++++------ .../hooks/useOnyxStateSearchSnapshot.test.tsx | 16 +++++++++++++ 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/contributingGuides/philosophies/ONYX-DATA-MANAGEMENT.md b/contributingGuides/philosophies/ONYX-DATA-MANAGEMENT.md index 23615db7908e..fc29d160eef7 100644 --- a/contributingGuides/philosophies/ONYX-DATA-MANAGEMENT.md +++ b/contributingGuides/philosophies/ONYX-DATA-MANAGEMENT.md @@ -72,7 +72,7 @@ It reads the cache once and never subscribes, so the value it returns MUST NOT r Read live data only when the read replaces a subscription that never went through the `useOnyx` redirection, such as a module-level `Onyx.connect()` used only from handlers. In that case, disable `rulesdir/no-onyx-get-snapshot-key` on that line with a reason after `--`. For `Onyx.multiGet()`, disable it on the line of the call, which covers every key in the list. For example: `// eslint-disable-next-line rulesdir/no-onyx-get-snapshot-key -- replaces a module-level Onyx.connect used only by handlers, never read a snapshot`. Disable one line at a time, always with a reason. Reviewers judge the reason. A read of the Concierge chat always needs the live report, in any Search scope. `Onyx.get()` may read `${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}` without a disable when `conciergeReportID` is a same-file `const` bound to a read of `ONYXKEYS.CONCIERGE_REPORT_ID`. ### - `useOnyxState` MUST be imported from `@hooks/useOnyxState` -`@hooks/useOnyxState` wraps the Onyx hook the same way `@hooks/useOnyx` wraps `useOnyx`. Inside a `SearchScopeProvider`, a selector that reads a key in `CONST.SEARCH.SNAPSHOT_ONYX_KEYS` gets the value from the current Search snapshot, and the hook subscribes to that snapshot instead of the live key. Every other key is read live. The Onyx hook always reads live keys, so importing it directly makes a component show live data on Search. Lint bans that import. +`@hooks/useOnyxState` wraps the Onyx hook the same way `@hooks/useOnyx` wraps `useOnyx`. Inside a `SearchScopeProvider`, a selector that reads a key in `CONST.SEARCH.SNAPSHOT_ONYX_KEYS` gets the value from the current Search snapshot, and the hook subscribes to that snapshot instead of the live key. Every other key is read live. The Onyx hook always reads live keys, so importing it directly makes a component show live data on Search. Lint bans that import. A value that must be the same on every screen, such as one that replaces an Onyx derived value, passes `shouldUseLiveData: true` to read every key live inside Search too. A selector that keeps a module-level cache MUST key it by the value it read, for example a `WeakMap` from the collection to the result. The same selector can run with snapshot data in one component and live data in another, so a cache that holds only the last input is evicted on every switch between the two. To compare with the previous input, read it from `previousState`, which goes through the same redirection. diff --git a/src/hooks/useOnyxState.ts b/src/hooks/useOnyxState.ts index ac37959035be..791c9c29c26f 100644 --- a/src/hooks/useOnyxState.ts +++ b/src/hooks/useOnyxState.ts @@ -76,28 +76,38 @@ function createSnapshotStateView(state: OnyxStateView, snapshotKey: SnapshotKey) ) as OnyxStateView; } -function useSearchSnapshotKey(): SnapshotKey | undefined { +function useSearchSnapshotKey(shouldUseLiveData: boolean): SnapshotKey | undefined { const isOnSearch = useIsOnSearch(); - if (!isOnSearch) { + if (!isOnSearch || shouldUseLiveData) { return undefined; } const {currentSearchHash} = use(SearchQueryContext); - const {shouldUseLiveData} = use(SearchResultsContext); - if (!currentSearchHash || shouldUseLiveData) { + const {shouldUseLiveData: shouldScreenUseLiveData} = use(SearchResultsContext); + if (!currentSearchHash || shouldScreenUseLiveData) { return undefined; } return `${ONYXKEYS.COLLECTION.SNAPSHOT}${currentSearchHash}`; } -function useOnyxState(selector: UseOnyxStateSelector, options?: UseOnyxStateOptions): T { - const snapshotKey = useSearchSnapshotKey(); +type UseOnyxStateWithSnapshotsOptions = UseOnyxStateOptions & { + /** + * Reads every key live, also inside Search. For values that must be the same on every screen, such as the ones that + * used to be Onyx derived values, which were always computed from live data. + */ + shouldUseLiveData?: boolean; +}; + +function useOnyxState(selector: UseOnyxStateSelector, options?: UseOnyxStateWithSnapshotsOptions): T { + const {shouldUseLiveData = false, ...onyxOptions} = options ?? {}; + const snapshotKey = useSearchSnapshotKey(shouldUseLiveData); const snapshotAwareSelector: UseOnyxStateSelector = snapshotKey ? (state, previousState) => selector(createSnapshotStateView(state, snapshotKey), previousState && createSnapshotStateView(previousState, snapshotKey)) : selector; - return useOnyxStateWithoutSnapshots(snapshotAwareSelector, options); + return useOnyxStateWithoutSnapshots(snapshotAwareSelector, onyxOptions); } export default useOnyxState; +export type {UseOnyxStateWithSnapshotsOptions}; diff --git a/tests/unit/hooks/useOnyxStateSearchSnapshot.test.tsx b/tests/unit/hooks/useOnyxStateSearchSnapshot.test.tsx index 2ddf3a6de85d..f96ce7ec5ddf 100644 --- a/tests/unit/hooks/useOnyxStateSearchSnapshot.test.tsx +++ b/tests/unit/hooks/useOnyxStateSearchSnapshot.test.tsx @@ -30,6 +30,8 @@ const OTHER_SNAPSHOT_REPORT: Report = {reportID: '1', reportName: 'Other snapsho const REPORT_MISSING_FROM_SNAPSHOT: Report = {reportID: '2', reportName: 'Live only report'}; const LIVE_SESSION_EMAIL = 'live@expensify.com'; +const LIVE_DATA_OPTIONS = {shouldUseLiveData: true}; + type SearchScreenProps = ChildrenProps & { isOnSearch?: boolean; shouldUseLiveData?: boolean; @@ -325,6 +327,20 @@ describe('useOnyxState Search snapshot updates', () => { expect(values.at(-1)).toEqual({reportName: OTHER_SNAPSHOT_REPORT.reportName, previousReportName: undefined}); }); + it('should read live data inside Search when the hook asks for live data', async () => { + // Given a report whose live and snapshot copies differ, read on a Search screen by a hook that asks for live data + const {result} = renderHook(() => useOnyxState(selectReport, LIVE_DATA_OPTIONS), {wrapper: SearchScreen}); + await waitForBatchedUpdatesWithAct(); + expect(result.current).toEqual(LIVE_REPORT); + + // When the live report is changed with a plain merge, which does not touch the snapshot + await act(() => Onyx.merge(REPORT_KEY, {reportName: 'Merged report'})); + await waitForBatchedUpdatesWithAct(); + + // Then the hook returns the new live value, because values that must be the same on every screen ignore the snapshot + expect(result.current).toEqual({...LIVE_REPORT, reportName: 'Merged report'}); + }); + it('should keep a consumer inside Search apart from one outside it', async () => { // Given the same selector rendered once on a Search screen and once outside any Search scope const {result: searchResult} = await renderSelector(selectReport, SearchScreen); From 50f6e41d3a98f01f1bb559f8b68f7ffdfff98f09 Mon Sep 17 00:00:00 2001 From: Hubert Sosinski Date: Wed, 18 Nov 2026 15:06:04 +0100 Subject: [PATCH 3/3] Pin Onyx to Expensify repo and trim useOnyxState wrapper --- oxlint.config.mts | 5 --- package-lock.json | 4 +- package.json | 2 +- src/hooks/useOnyxState.ts | 17 -------- .../hooks/useOnyxStateSearchSnapshot.test.tsx | 42 +------------------ 5 files changed, 5 insertions(+), 65 deletions(-) diff --git a/oxlint.config.mts b/oxlint.config.mts index 8742b5817b28..00e607895213 100644 --- a/oxlint.config.mts +++ b/oxlint.config.mts @@ -68,11 +68,6 @@ const restrictedImportPaths = [ {name: 'lodash', importNames: ['isEqual'], message: "Please use 'deepEqual' from 'fast-equals' instead."}, {name: 'react-native-onyx', importNames: ['useOnyx'], message: "Please use '@hooks/useOnyx' instead."}, {name: 'react-native-onyx', importNames: ['useOnyxState'], message: "Please use '@hooks/useOnyxState' instead."}, - { - name: 'react-native-onyx/dist/useOnyxState', - message: "Please use '@hooks/useOnyxState' instead. Type-only imports are still allowed.", - allowTypeImports: true, - }, {name: '@src/utils/findNodeHandle', message: "Do not use 'findNodeHandle' as it is no longer supported on web."}, ]; diff --git a/package-lock.json b/package-lock.json index 2600debcf600..beb1d4311df4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -129,7 +129,7 @@ "react-native-nitro-image": "0.15.2", "react-native-nitro-modules": "0.37.1", "react-native-nitro-sqlite": "10.2.0", - "react-native-onyx": "git+https://github.com/callstack-internal/react-native-onyx.git#9b4cc4a7f6a070f5941196dcd45dcb2534f6592f", + "react-native-onyx": "git+https://github.com/Expensify/react-native-onyx.git#9b4cc4a7f6a070f5941196dcd45dcb2534f6592f", "react-native-pager-view": "9.0.4", "react-native-pdf": "7.0.2", "react-native-permissions": "^5.6.3", @@ -38527,7 +38527,7 @@ }, "node_modules/react-native-onyx": { "version": "3.0.155", - "resolved": "git+ssh://git@github.com/callstack-internal/react-native-onyx.git#9b4cc4a7f6a070f5941196dcd45dcb2534f6592f", + "resolved": "git+ssh://git@github.com/Expensify/react-native-onyx.git#9b4cc4a7f6a070f5941196dcd45dcb2534f6592f", "integrity": "sha512-6cUo+I+K/Ady1sEvXBVn4tCpAVNNeLsMfeN7Z+m7IZevB+aII65EzUvklqAk54u76/1LEYpPgXHxFDBd0tB23A==", "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index 7d3bc17f687c..b88a18e88f42 100644 --- a/package.json +++ b/package.json @@ -205,7 +205,7 @@ "react-native-nitro-image": "0.15.2", "react-native-nitro-modules": "0.37.1", "react-native-nitro-sqlite": "10.2.0", - "react-native-onyx": "git+https://github.com/callstack-internal/react-native-onyx.git#9b4cc4a7f6a070f5941196dcd45dcb2534f6592f", + "react-native-onyx": "git+https://github.com/Expensify/react-native-onyx.git#9b4cc4a7f6a070f5941196dcd45dcb2534f6592f", "react-native-pager-view": "9.0.4", "react-native-pdf": "7.0.2", "react-native-permissions": "^5.6.3", diff --git a/src/hooks/useOnyxState.ts b/src/hooks/useOnyxState.ts index 791c9c29c26f..58b54239602d 100644 --- a/src/hooks/useOnyxState.ts +++ b/src/hooks/useOnyxState.ts @@ -1,7 +1,3 @@ -/** - * `useOnyxState` with Search snapshot support. Inside a Search scope the selector reads the keys in - * `CONST.SEARCH.SNAPSHOT_ONYX_KEYS` from the current Search snapshot, the same way `@hooks/useOnyx` does. - */ import {SearchQueryContext, SearchResultsContext} from '@components/Search/SearchContext'; import {useIsOnSearch} from '@components/Search/SearchScopeProvider'; @@ -23,10 +19,6 @@ type SnapshotKey = `${typeof ONYXKEYS.COLLECTION.SNAPSHOT}${string}`; const collectionsBySnapshotData = new WeakMap, Map>(); -/** - * Reads a key out of a Search snapshot. A collection root returns the same object for as long as the snapshot's `data` stays - * the same, because selectors compare their inputs by reference and a collection rebuilt on every read would always look changed. - */ function getSnapshotKeyData(snapshot: SearchResults | undefined, key: OnyxKey): unknown { const data = snapshot?.data; if (!snapshot || !data) { @@ -47,10 +39,6 @@ function getSnapshotKeyData(snapshot: SearchResults | undefined, key: OnyxKey): return collections.get(key); } -/** - * Wraps a state view so that snapshot keys are answered from the Search snapshot. The read of the snapshot goes through - * `state`, so `useOnyxState` subscribes to the snapshot instead of the live key. - */ function createSnapshotStateView(state: OnyxStateView, snapshotKey: SnapshotKey): OnyxStateView { const read = (key: string | symbol): unknown => { if (typeof key !== 'string') { @@ -91,10 +79,6 @@ function useSearchSnapshotKey(shouldUseLiveData: boolean): SnapshotKey | undefin } type UseOnyxStateWithSnapshotsOptions = UseOnyxStateOptions & { - /** - * Reads every key live, also inside Search. For values that must be the same on every screen, such as the ones that - * used to be Onyx derived values, which were always computed from live data. - */ shouldUseLiveData?: boolean; }; @@ -110,4 +94,3 @@ function useOnyxState(selector: UseOnyxStateSelector, options?: UseOnyxSta } export default useOnyxState; -export type {UseOnyxStateWithSnapshotsOptions}; diff --git a/tests/unit/hooks/useOnyxStateSearchSnapshot.test.tsx b/tests/unit/hooks/useOnyxStateSearchSnapshot.test.tsx index f96ce7ec5ddf..9582ba5c0c19 100644 --- a/tests/unit/hooks/useOnyxStateSearchSnapshot.test.tsx +++ b/tests/unit/hooks/useOnyxStateSearchSnapshot.test.tsx @@ -33,19 +33,18 @@ const LIVE_SESSION_EMAIL = 'live@expensify.com'; const LIVE_DATA_OPTIONS = {shouldUseLiveData: true}; type SearchScreenProps = ChildrenProps & { - isOnSearch?: boolean; shouldUseLiveData?: boolean; searchHash?: number; }; -function SearchScreen({children, isOnSearch = true, shouldUseLiveData = false, searchHash = SEARCH_HASH}: SearchScreenProps) { +function SearchScreen({children, shouldUseLiveData = false, searchHash = SEARCH_HASH}: SearchScreenProps) { const queryContext = use(SearchQueryContext); const resultsContext = use(SearchResultsContext); const queryContextWithHash = useMemo(() => ({...queryContext, currentSearchHash: searchHash}), [queryContext, searchHash]); const resultsContextWithLiveData = useMemo(() => ({...resultsContext, shouldUseLiveData}), [resultsContext, shouldUseLiveData]); return ( - + {children} @@ -57,10 +56,6 @@ function SearchScreenWithLiveData({children}: ChildrenProps) { return {children}; } -function SearchScreenOutsideSearchScope({children}: ChildrenProps) { - return {children}; -} - function selectReport(state: OnyxStateView) { return state[REPORT_KEY]; } @@ -168,15 +163,6 @@ describe('useOnyxState Search snapshot redirect', () => { expect(result.current).toEqual(LIVE_REPORT); }); - it('should read live data when the Search scope is turned off', async () => { - // Given a Search screen with a search hash but a scope marked as not on Search - // When a selector reads a report on that screen - const {result} = await renderSelector(selectReport, SearchScreenOutsideSearchScope); - - // Then the live copy is returned because the scope decides whether snapshots apply - expect(result.current).toEqual(LIVE_REPORT); - }); - it('should read live data inside Search for keys that snapshots do not copy', async () => { // Given a live session, which snapshots never hold // When a selector reads it on a Search screen @@ -251,16 +237,6 @@ describe('useOnyxState Search snapshot redirect', () => { // Then the selector is not run again, because the redirect must not defeat the skip that useOnyxState does for unchanged inputs expect(selector.mock.calls.length).toBe(runsAfterMount); }); -}); - -describe('useOnyxState Search snapshot updates', () => { - beforeEach(async () => { - await Onyx.clear(); - await Onyx.set(REPORT_KEY, LIVE_REPORT); - await Onyx.merge(SNAPSHOT_KEY, {data: {[REPORT_KEY]: SNAPSHOT_REPORT}}); - await Onyx.merge(OTHER_SNAPSHOT_KEY, {data: {[REPORT_KEY]: OTHER_SNAPSHOT_REPORT}}); - await waitForBatchedUpdatesWithAct(); - }); it('should not run the selector inside Search after a plain merge to live data', async () => { // Given a selector that reads a report on a Search screen @@ -340,18 +316,4 @@ describe('useOnyxState Search snapshot updates', () => { // Then the hook returns the new live value, because values that must be the same on every screen ignore the snapshot expect(result.current).toEqual({...LIVE_REPORT, reportName: 'Merged report'}); }); - - it('should keep a consumer inside Search apart from one outside it', async () => { - // Given the same selector rendered once on a Search screen and once outside any Search scope - const {result: searchResult} = await renderSelector(selectReport, SearchScreen); - const {result: liveResult} = await renderSelector(selectReport); - - // When the live report is changed with a plain merge - await act(() => Onyx.merge(REPORT_KEY, {reportName: 'Merged report'})); - await waitForBatchedUpdatesWithAct(); - - // Then only the outside consumer sees the change, because each one reads from its own source - expect(liveResult.current).toEqual({...LIVE_REPORT, reportName: 'Merged report'}); - expect(searchResult.current).toEqual(SNAPSHOT_REPORT); - }); });