Skip to content
Merged
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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,10 +257,10 @@ export default MyComponent;
This will add a prop to the component called `allReports` which is an object of collection member key/values. Changes to the individual member keys will modify the entire object and new props will be passed with each individual key update. The prop doesn't update on the initial rendering of the component until the entire collection has been read out of Onyx.

```js
Onyx.connect({key: ONYXKEYS.COLLECTION.REPORT}, callback: (allReports, collectionKey, sourceValue) => {...});
Onyx.connect({key: ONYXKEYS.COLLECTION.REPORT}, callback: (allReports, collectionKey) => {...});
```

This will fire the callback once with the entire collection initially and later with an updated version of the collection when individual keys update. The `sourceValue` parameter contains only the specific keys and values that triggered the current update, which can be useful for optimizing your code to only process what changed.
This will fire the callback once with the entire collection initially and later with an updated version of the collection when individual keys update.

### Performance Considerations When Using Collections

Expand Down
14 changes: 2 additions & 12 deletions lib/OnyxConnectionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,6 @@ type ConnectionMetadata = {
* The last callback key returned by `OnyxUtils.subscribeToKey()`'s callback.
*/
cachedCallbackKey?: OnyxKey;

/**
* The value that triggered the last update
*/
sourceValue?: OnyxValue<OnyxKey>;
};

/**
Expand Down Expand Up @@ -138,11 +133,7 @@ class OnyxConnectionManager {
for (const callback of connection.callbacks.values()) {
try {
if (OnyxKeys.isCollectionKey(connection.onyxKey)) {
(callback as CollectionConnectCallback<OnyxKey>)(
connection.cachedCallbackValue as Record<string, unknown>,
connection.cachedCallbackKey as OnyxKey,
connection.sourceValue,
);
(callback as CollectionConnectCallback<OnyxKey>)(connection.cachedCallbackValue as Record<string, unknown>, connection.cachedCallbackKey as OnyxKey);
} else {
(callback as DefaultConnectCallback<OnyxKey>)(connection.cachedCallbackValue, connection.cachedCallbackKey as OnyxKey);
}
Expand All @@ -167,15 +158,14 @@ class OnyxConnectionManager {

// If there is no connection yet for that connection ID, we create a new one.
if (!connectionMetadata) {
const callback: ConnectCallback = (value, key, sourceValue) => {
const callback: ConnectCallback = (value: OnyxValue<OnyxKey>, key: OnyxKey) => {
const createdConnection = this.connectionsMap.get(connectionID);
if (createdConnection) {
// We signal that the first connection was made and now any new subscribers
// can fire their callbacks immediately with the cached value when connecting.
createdConnection.isConnectionMade = true;
createdConnection.cachedCallbackValue = value;
createdConnection.cachedCallbackKey = key;
createdConnection.sourceValue = sourceValue;
this.fireCallbacks(connectionID);
}
};
Expand Down
5 changes: 2 additions & 3 deletions lib/OnyxUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import StorageCircuitBreaker from './StorageCircuitBreaker';
import Storage from './storage';
import {StorageErrorClass} from './storage/errors';
import type {
CollectionConnectCallback,
CollectionKeyBase,
ConnectOptions,
DeepRecord,
Expand Down Expand Up @@ -581,7 +580,7 @@ function keysChanged<TKey extends CollectionKeyBase>(

try {
lastConnectionCallbackData.set(subscriber.subscriptionID, {value: cachedCollection, matchedKey: subscriber.key});
subscriber.callback(cachedCollection, subscriber.key, partialCollection);
subscriber.callback(cachedCollection, subscriber.key);
} catch (error) {
Logger.logAlert(`[OnyxUtils.keysChanged] Subscriber callback threw an error for key '${collectionKey}': ${error}`);
}
Expand Down Expand Up @@ -676,7 +675,7 @@ function keyChanged<TKey extends OnyxKey>(
cachedCollections[subscriber.key] = cachedCollection;
}
lastConnectionCallbackData.set(subscriber.subscriptionID, {value: cachedCollection, matchedKey: subscriber.key});
(subscriber.callback as CollectionConnectCallback<OnyxKey>)(cachedCollection, subscriber.key, {[key]: value});
subscriber.callback(cachedCollection, subscriber.key);
continue;
}

Expand Down
10 changes: 3 additions & 7 deletions lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,14 +223,14 @@ type BaseConnectOptions = {
type DefaultConnectCallback<TKey extends OnyxKey> = (value: OnyxEntry<KeyValueMapping[TKey]>, key: TKey) => void;

/** Represents the callback function used in `Onyx.connect()` method with a collection key. */
type CollectionConnectCallback<TKey extends OnyxKey> = (value: NonUndefined<OnyxCollection<KeyValueMapping[TKey]>>, key: TKey, sourceValue?: OnyxValue<TKey>) => void;
type CollectionConnectCallback<TKey extends OnyxKey> = (value: NonUndefined<OnyxCollection<KeyValueMapping[TKey]>>, key: TKey) => void;
Comment thread
fabioh8010 marked this conversation as resolved.

/**
* Represents the options used in `Onyx.connect()` method.
*
* For a collection root key (e.g. `ONYXKEYS.COLLECTION.REPORT`), the callback fires
* with the entire collection object whenever any member changes (signature
* `(collection, key, sourceValue)`). For any other key, the callback fires with the value at
* `(collection, key)`). For any other key, the callback fires with the value at
* that key (signature `(value, key)`).
*/
// NOTE: Any changes to this type like adding or removing options must be accounted in OnyxConnectionManager's `generateConnectionID()` method!
Expand All @@ -239,11 +239,7 @@ type ConnectOptions<TKey extends OnyxKey> = BaseConnectOptions & {
key: TKey;

/** A function that will be called when the Onyx data we are subscribed changes. */
callback?: (
value: TKey extends CollectionKeyBase ? NonUndefined<OnyxCollection<KeyValueMapping[TKey]>> : OnyxEntry<KeyValueMapping[TKey]>,
key: TKey,
sourceValue?: TKey extends CollectionKeyBase ? NonUndefined<OnyxCollection<KeyValueMapping[TKey]>> : never,
) => void;
callback?: (value: TKey extends CollectionKeyBase ? NonUndefined<OnyxCollection<KeyValueMapping[TKey]>> : OnyxEntry<KeyValueMapping[TKey]>, key: TKey) => void;
};

type CallbackToStateMapping<TKey extends OnyxKey> = ConnectOptions<TKey> & {
Expand Down
15 changes: 3 additions & 12 deletions lib/useOnyx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,11 @@ type UseOnyxOptions<TKey extends OnyxKey, TReturnValue> = {

type FetchStatus = 'loading' | 'loaded';

type ResultMetadata<TValue> = {
type ResultMetadata = {
status: FetchStatus;
sourceValue?: NonNullable<TValue> | undefined;
};

type UseOnyxResult<TValue> = [NonNullable<TValue> | undefined, ResultMetadata<TValue>];
type UseOnyxResult<TValue> = [NonNullable<TValue> | undefined, ResultMetadata];

function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(
key: TKey,
Expand Down Expand Up @@ -117,9 +116,6 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(
// Indicates if we should get the newest cached value from Onyx during `getSnapshot()` execution.
const shouldGetCachedValueRef = useRef(true);

// Inside useOnyx.ts, we need to track the sourceValue separately
const sourceValueRef = useRef<NonNullable<TReturnValue> | undefined>(undefined);

// Cache the options key to avoid regenerating it every getSnapshot call
const cacheKey = useMemo(
() =>
Expand Down Expand Up @@ -226,7 +222,6 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(
previousValueRef.current ?? undefined,
{
status: newFetchStatus,
sourceValue: sourceValueRef.current,
},
];
}
Expand All @@ -246,7 +241,6 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(
if (hasMountedRef.current) {
previousValueRef.current = null;
newValueRef.current = null;
sourceValueRef.current = undefined;
resultRef.current = [undefined, {status: 'loading'}];
shouldGetCachedValueRef.current = true;
}
Expand All @@ -257,7 +251,7 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(

connectionRef.current = connectionManager.connect<CollectionKeyBase>({
key,
callback: (value, callbackKey, sourceValue) => {
callback: () => {
isConnectingRef.current = false;
onStoreChangeFnRef.current = onStoreChange;

Expand All @@ -268,9 +262,6 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(
// Signals that we want to get the newest cached value again in `getSnapshot()`.
shouldGetCachedValueRef.current = true;

// sourceValue is unknown type, so we need to cast it to the correct type.
sourceValueRef.current = sourceValue as NonNullable<TReturnValue>;

// Invalidate snapshot cache for this key when data changes
onyxSnapshotCache.invalidateForKey(key);

Expand Down
18 changes: 3 additions & 15 deletions tests/perf-test/OnyxSnapshotCache.perf-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,9 @@ const complexSelectorOptions: UseOnyxOptions<string, ComplexSelectorResult> = {
};

// Mock results
const mockResult: UseOnyxResult<MockData> = [
{id: 1, name: 'Test', value: 42},
{status: 'loaded', sourceValue: {id: 1, name: 'Test', value: 42}},
];
const mockResult: UseOnyxResult<MockData> = [{id: 1, name: 'Test', value: 42}, {status: 'loaded'}];

const mockResults = Array.from(
{length: 1000},
(_, i): UseOnyxResult<MockData> => [
{id: i, name: `Test${i}`, value: i * 10},
{status: 'loaded', sourceValue: {id: i, name: `Test${i}`, value: i * 10}},
],
);
const mockResults = Array.from({length: 1000}, (_, i): UseOnyxResult<MockData> => [{id: i, name: `Test${i}`, value: i * 10}, {status: 'loaded'}]);

describe('OnyxSnapshotCache', () => {
let cache: OnyxSnapshotCache;
Expand Down Expand Up @@ -153,10 +144,7 @@ describe('OnyxSnapshotCache', () => {

test('getting cached result with complex selector (cache hit)', async () => {
const cacheKey = cache.registerConsumer(ONYXKEYS.TEST_KEY, complexSelectorOptions);
const complexResult: UseOnyxResult<ComplexSelectorResult> = [
{id: 1, name: 'Test', computed: 84, formatted: 'Test: 42'},
{status: 'loaded', sourceValue: {id: 1, name: 'Test', computed: 84, formatted: 'Test: 42'}},
];
const complexResult: UseOnyxResult<ComplexSelectorResult> = [{id: 1, name: 'Test', computed: 84, formatted: 'Test: 42'}, {status: 'loaded'}];
await measureFunction(
() => {
cache.getCachedResult(ONYXKEYS.TEST_KEY, cacheKey);
Expand Down
2 changes: 1 addition & 1 deletion tests/perf-test/useOnyx.perf-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const metadataStatusMatcher = (onyxKey: OnyxKey, expected: FetchStatus) => `meta
type UseOnyxMatcherProps = {
onyxKey: OnyxKey;
data: OnyxValue<OnyxKey>;
metadata: ResultMetadata<OnyxValue<OnyxKey>>;
metadata: ResultMetadata;
};

function UseOnyxMatcher({onyxKey, data, metadata}: UseOnyxMatcherProps) {
Expand Down
17 changes: 8 additions & 9 deletions tests/unit/OnyxConnectionManagerTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,8 @@ describe('OnyxConnectionManager', () => {
await act(async () => waitForPromisesToResolve());

// Both subscribers share the connection and receive the whole collection object.
expect(callback1).toHaveBeenCalledWith(collection, ONYXKEYS.COLLECTION.TEST_KEY, undefined);
expect(callback2).toHaveBeenCalledWith(collection, ONYXKEYS.COLLECTION.TEST_KEY, undefined);
expect(callback1).toHaveBeenCalledWith(collection, ONYXKEYS.COLLECTION.TEST_KEY);
expect(callback2).toHaveBeenCalledWith(collection, ONYXKEYS.COLLECTION.TEST_KEY);

connectionManager.disconnect(connection1);
connectionManager.disconnect(connection2);
Expand Down Expand Up @@ -232,7 +232,7 @@ describe('OnyxConnectionManager', () => {

await act(async () => waitForPromisesToResolve());

expect(callback1).toHaveBeenCalledWith(collection, ONYXKEYS.COLLECTION.TEST_KEY, undefined);
expect(callback1).toHaveBeenCalledWith(collection, ONYXKEYS.COLLECTION.TEST_KEY);

const callback2 = jest.fn();
const connection2 = connectionManager.connect({key: ONYXKEYS.COLLECTION.TEST_KEY, callback: callback2});
Expand Down Expand Up @@ -402,8 +402,8 @@ describe('OnyxConnectionManager', () => {
});
});

describe('sourceValue parameter', () => {
it('should pass the sourceValue parameter to collection-root callbacks', async () => {
describe('collection callback arguments', () => {
it('should call collection-root callbacks with only the value and key', async () => {
const obj1 = {id: 'entry1_id', name: 'entry1_name'};
const obj2 = {id: 'entry2_id', name: 'entry2_name'};

Expand All @@ -417,7 +417,7 @@ describe('OnyxConnectionManager', () => {

// Initial callback with undefined values
expect(callback).toHaveBeenCalledTimes(1);
expect(callback).toHaveBeenCalledWith(undefined, ONYXKEYS.COLLECTION.TEST_KEY, undefined);
expect(callback).toHaveBeenCalledWith(undefined, ONYXKEYS.COLLECTION.TEST_KEY);

// Reset mock to test the next update
callback.mockReset();
Expand All @@ -426,7 +426,7 @@ describe('OnyxConnectionManager', () => {
await Onyx.merge(`${ONYXKEYS.COLLECTION.TEST_KEY}entry1`, obj1);

expect(callback).toHaveBeenCalledTimes(1);
expect(callback).toHaveBeenCalledWith({[`${ONYXKEYS.COLLECTION.TEST_KEY}entry1`]: obj1}, ONYXKEYS.COLLECTION.TEST_KEY, {[`${ONYXKEYS.COLLECTION.TEST_KEY}entry1`]: obj1});
expect(callback).toHaveBeenCalledWith({[`${ONYXKEYS.COLLECTION.TEST_KEY}entry1`]: obj1}, ONYXKEYS.COLLECTION.TEST_KEY);

// Reset mock to test the next update
callback.mockReset();
Expand All @@ -441,13 +441,12 @@ describe('OnyxConnectionManager', () => {
[`${ONYXKEYS.COLLECTION.TEST_KEY}entry2`]: obj2,
},
ONYXKEYS.COLLECTION.TEST_KEY,
{[`${ONYXKEYS.COLLECTION.TEST_KEY}entry2`]: obj2},
);

connectionManager.disconnect(connection);
});

it('should not pass sourceValue to regular (non-collection) key callbacks', async () => {
it('should call regular (non-collection) key callbacks with only the value and key', async () => {
const obj1 = {id: 'entry1_id', name: 'entry1_name'};

const callback = jest.fn();
Expand Down
15 changes: 2 additions & 13 deletions tests/unit/onyxClearWebStorageTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ describe('Set data while storage is clearing', () => {
expect(collectionCallback).toHaveBeenCalledTimes(3);

// And it should be called with the expected parameters each time
expect(collectionCallback).toHaveBeenNthCalledWith(1, undefined, ONYX_KEYS.COLLECTION.TEST, undefined);
expect(collectionCallback).toHaveBeenNthCalledWith(1, undefined, ONYX_KEYS.COLLECTION.TEST);
expect(collectionCallback).toHaveBeenNthCalledWith(
2,
{
Expand All @@ -249,19 +249,8 @@ describe('Set data while storage is clearing', () => {
test_4: 4,
},
ONYX_KEYS.COLLECTION.TEST,
{
test_1: 1,
test_2: 2,
test_3: 3,
test_4: 4,
},
);
expect(collectionCallback).toHaveBeenLastCalledWith({}, ONYX_KEYS.COLLECTION.TEST, {
test_1: undefined,
test_2: undefined,
test_3: undefined,
test_4: undefined,
});
expect(collectionCallback).toHaveBeenLastCalledWith({}, ONYX_KEYS.COLLECTION.TEST);
})
);
});
Expand Down
Loading
Loading