Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions __mocks__/react-native-onyx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -41,4 +41,4 @@ const reactNativeOnyxMock: ReactNativeOnyxMock = {

export default reactNativeOnyxMock;

export {useOnyx};
export {useOnyx, useOnyxState};
5 changes: 5 additions & 0 deletions contributingGuides/philosophies/ONYX-DATA-MANAGEMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
1 change: 1 addition & 0 deletions oxlint.config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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."},
];

Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": "3.0.143",
"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",
Expand Down
1 change: 1 addition & 0 deletions src/hooks/useOnyx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,4 @@ const useOnyx: UseOnyxWithoutSnapshots = <TKey extends OnyxKey, TReturnValue = O
};

export default useOnyx;
export {getKeyData};
96 changes: 96 additions & 0 deletions src/hooks/useOnyxState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import {SearchQueryContext, SearchResultsContext} from '@components/Search/SearchContext';
import {useIsOnSearch} from '@components/Search/SearchScopeProvider';

import isSnapshotCompatibleKey from '@libs/SnapshotUtils';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {SearchResults} from '@src/types/onyx';

import type {OnyxKey, OnyxStateView, UseOnyxStateOptions, UseOnyxStateSelector} from 'react-native-onyx';

import {use} from 'react';
// eslint-disable-next-line no-restricted-imports -- this wrapper is the one place that may import the Onyx hook
import {useOnyxState as useOnyxStateWithoutSnapshots} from 'react-native-onyx';

import {getKeyData} from './useOnyx';

type SnapshotKey = `${typeof ONYXKEYS.COLLECTION.SNAPSHOT}${string}`;

const collectionsBySnapshotData = new WeakMap<NonNullable<SearchResults['data']>, Map<OnyxKey, unknown>>();

function getSnapshotKeyData(snapshot: SearchResults | undefined, key: OnyxKey): unknown {
const data = snapshot?.data;
if (!snapshot || !data) {
return undefined;
}
if (!key.endsWith('_')) {
return getKeyData<OnyxKey, unknown>(snapshot, key);
}

let collections = collectionsBySnapshotData.get(data);
if (!collections) {
collections = new Map();
collectionsBySnapshotData.set(data, collections);
}
if (!collections.has(key)) {
collections.set(key, getKeyData<OnyxKey, unknown>(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<T> = UseOnyxStateOptions<T> & {
shouldUseLiveData?: boolean;
};

function useOnyxState<T>(selector: UseOnyxStateSelector<T>, options?: UseOnyxStateWithSnapshotsOptions<T>): T {
const {shouldUseLiveData = false, ...onyxOptions} = options ?? {};
const snapshotKey = useSearchSnapshotKey(shouldUseLiveData);

const snapshotAwareSelector: UseOnyxStateSelector<T> = snapshotKey
? (state, previousState) => selector(createSnapshotStateView(state, snapshotKey), previousState && createSnapshotStateView(previousState, snapshotKey))
: selector;

return useOnyxStateWithoutSnapshots(snapshotAwareSelector, onyxOptions);
}

export default useOnyxState;
Loading
Loading