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..fc29d160eef7 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 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. + ### - 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..00e607895213 100644 --- a/oxlint.config.mts +++ b/oxlint.config.mts @@ -67,6 +67,7 @@ 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: '@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..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/Expensify/react-native-onyx.git#b63721334b5a41f527d78bd1c12e2aae7241c5c7", + "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/Expensify/react-native-onyx.git#b63721334b5a41f527d78bd1c12e2aae7241c5c7", + "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 4f5bb36eadb1..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/Expensify/react-native-onyx.git#b63721334b5a41f527d78bd1c12e2aae7241c5c7", + "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/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>(); + +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); +} + +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(shouldUseLiveData: boolean): SnapshotKey | undefined { + const isOnSearch = useIsOnSearch(); + if (!isOnSearch || shouldUseLiveData) { + return undefined; + } + + const {currentSearchHash} = use(SearchQueryContext); + const {shouldUseLiveData: shouldScreenUseLiveData} = use(SearchResultsContext); + if (!currentSearchHash || shouldScreenUseLiveData) { + return undefined; + } + return `${ONYXKEYS.COLLECTION.SNAPSHOT}${currentSearchHash}`; +} + +type UseOnyxStateWithSnapshotsOptions = UseOnyxStateOptions & { + 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, onyxOptions); +} + +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..9582ba5c0c19 --- /dev/null +++ b/tests/unit/hooks/useOnyxStateSearchSnapshot.test.tsx @@ -0,0 +1,319 @@ +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'; + +const LIVE_DATA_OPTIONS = {shouldUseLiveData: true}; + +type SearchScreenProps = ChildrenProps & { + shouldUseLiveData?: boolean; + searchHash?: number; +}; + +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} + + + ); +} + +function SearchScreenWithLiveData({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 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); + }); + + 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 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'}); + }); +});