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
10 changes: 2 additions & 8 deletions lib/OnyxConnectionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,6 @@ type ConnectionMetadata = {
*/
cachedCallbackKey?: OnyxKey;

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

/**
* Whether the subscriber is waiting for the collection callback to be fired.
*/
Expand Down Expand Up @@ -143,7 +138,7 @@ class OnyxConnectionManager {

for (const callback of connection.callbacks.values()) {
if (connection.waitForCollectionCallback) {
(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 @@ -165,15 +160,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
4 changes: 2 additions & 2 deletions lib/OnyxUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -600,7 +600,7 @@ function keysChanged<TKey extends CollectionKeyBase>(
lastConnectionCallbackData.set(subscriber.subscriptionID, {value: cachedCollection, matchedKey: subscriber.key});

if (subscriber.waitForCollectionCallback) {
subscriber.callback(cachedCollection, subscriber.key, partialCollection);
subscriber.callback(cachedCollection, subscriber.key);
continue;
}

Expand Down Expand Up @@ -710,7 +710,7 @@ function keyChanged<TKey extends OnyxKey>(
cachedCollections[subscriber.key] = cachedCollection;
}
lastConnectionCallbackData.set(subscriber.subscriptionID, {value: cachedCollection, matchedKey: subscriber.key});
subscriber.callback(cachedCollection, subscriber.key, {[key]: value});
subscriber.callback(cachedCollection, subscriber.key);
continue;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ 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;

/** Represents the options used in `Onyx.connect()` method with a regular key. */
// NOTE: Any changes to this type like adding or removing options must be accounted in OnyxConnectionManager's `generateConnectionID()` method!
Expand Down
15 changes: 3 additions & 12 deletions lib/useOnyx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,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 @@ -118,9 +117,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 @@ -227,7 +223,6 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(
previousValueRef.current ?? undefined,
{
status: newFetchStatus,
sourceValue: sourceValueRef.current,
},
];
}
Expand All @@ -247,7 +242,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 @@ -258,7 +252,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 @@ -269,9 +263,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
13 changes: 6 additions & 7 deletions tests/unit/OnyxConnectionManagerTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ describe('OnyxConnectionManager', () => {
expect(callback1).toHaveBeenNthCalledWith(2, obj2, `${ONYXKEYS.COLLECTION.TEST_KEY}entry2`);

expect(callback2).toHaveBeenCalledTimes(1);
expect(callback2).toHaveBeenCalledWith(collection, ONYXKEYS.COLLECTION.TEST_KEY, undefined);
expect(callback2).toHaveBeenCalledWith(collection, ONYXKEYS.COLLECTION.TEST_KEY);

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

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

Expand All @@ -428,7 +428,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 @@ -437,7 +437,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 @@ -452,13 +452,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 callbacks when waitForCollectionCallback is false', async () => {
it('should call regular callbacks with only value and key when waitForCollectionCallback is false', 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 @@ -240,7 +240,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 @@ -250,19 +250,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
29 changes: 10 additions & 19 deletions tests/unit/onyxTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1065,7 +1065,7 @@ describe('Onyx', () => {
.then(() => {
// Then we expect the callback to be called only once and the initial stored value to be initialCollectionData
expect(mockCallback).toHaveBeenCalledTimes(1);
expect(mockCallback).toHaveBeenCalledWith(initialCollectionData, ONYX_KEYS.COLLECTION.TEST_CONNECT_COLLECTION, undefined);
expect(mockCallback).toHaveBeenCalledWith(initialCollectionData, ONYX_KEYS.COLLECTION.TEST_CONNECT_COLLECTION);
});
});

Expand All @@ -1091,10 +1091,10 @@ describe('Onyx', () => {
expect(mockCallback).toHaveBeenCalledTimes(2);

// AND the value for the first call should be null since the collection was not initialized at that point
expect(mockCallback).toHaveBeenNthCalledWith(1, undefined, ONYX_KEYS.COLLECTION.TEST_POLICY, undefined);
expect(mockCallback).toHaveBeenNthCalledWith(1, undefined, ONYX_KEYS.COLLECTION.TEST_POLICY);

// AND the value for the second call should be collectionUpdate since the collection was updated
expect(mockCallback).toHaveBeenNthCalledWith(2, collectionUpdate, ONYX_KEYS.COLLECTION.TEST_POLICY, collectionUpdate);
expect(mockCallback).toHaveBeenNthCalledWith(2, collectionUpdate, ONYX_KEYS.COLLECTION.TEST_POLICY);
})
);
});
Expand Down Expand Up @@ -1149,10 +1149,8 @@ describe('Onyx', () => {
expect(mockCallback).toHaveBeenCalledTimes(2);

// AND the value for the second call should be collectionUpdate
expect(mockCallback).toHaveBeenNthCalledWith(1, undefined, ONYX_KEYS.COLLECTION.TEST_POLICY, undefined);
expect(mockCallback).toHaveBeenNthCalledWith(2, collectionUpdate, ONYX_KEYS.COLLECTION.TEST_POLICY, {
[`${ONYX_KEYS.COLLECTION.TEST_POLICY}1`]: collectionUpdate.testPolicy_1,
});
expect(mockCallback).toHaveBeenNthCalledWith(1, undefined, ONYX_KEYS.COLLECTION.TEST_POLICY);
expect(mockCallback).toHaveBeenNthCalledWith(2, collectionUpdate, ONYX_KEYS.COLLECTION.TEST_POLICY);
})
);
});
Expand Down Expand Up @@ -1187,7 +1185,7 @@ describe('Onyx', () => {
expect(mockCallback).toHaveBeenCalledTimes(2);

// And the value for the second call should be collectionUpdate
expect(mockCallback).toHaveBeenNthCalledWith(2, collectionUpdate, ONYX_KEYS.COLLECTION.TEST_POLICY, {testPolicy_1: collectionUpdate.testPolicy_1});
expect(mockCallback).toHaveBeenNthCalledWith(2, collectionUpdate, ONYX_KEYS.COLLECTION.TEST_POLICY);
})

// When merge is called again with the same collection not modified
Expand Down Expand Up @@ -1224,8 +1222,8 @@ describe('Onyx', () => {
{onyxMethod: Onyx.METHOD.MERGE_COLLECTION, key: ONYX_KEYS.COLLECTION.TEST_UPDATE, value: {[itemKey]: {a: 'a'}} as GenericCollection},
]).then(() => {
expect(collectionCallback).toHaveBeenCalledTimes(2);
expect(collectionCallback).toHaveBeenNthCalledWith(1, undefined, ONYX_KEYS.COLLECTION.TEST_UPDATE, undefined);
expect(collectionCallback).toHaveBeenNthCalledWith(2, {[itemKey]: {a: 'a'}}, ONYX_KEYS.COLLECTION.TEST_UPDATE, {[itemKey]: {a: 'a'}});
expect(collectionCallback).toHaveBeenNthCalledWith(1, undefined, ONYX_KEYS.COLLECTION.TEST_UPDATE);
expect(collectionCallback).toHaveBeenNthCalledWith(2, {[itemKey]: {a: 'a'}}, ONYX_KEYS.COLLECTION.TEST_UPDATE);

expect(testCallback).toHaveBeenCalledTimes(2);
expect(testCallback).toHaveBeenNthCalledWith(1, undefined, undefined);
Expand Down Expand Up @@ -1483,8 +1481,8 @@ describe('Onyx', () => {
})
.then(() => {
expect(collectionCallback).toHaveBeenCalledTimes(2);
expect(collectionCallback).toHaveBeenNthCalledWith(1, {[cat]: initialValue}, ONYX_KEYS.COLLECTION.ANIMALS, {[cat]: initialValue});
expect(collectionCallback).toHaveBeenNthCalledWith(2, collectionDiff, ONYX_KEYS.COLLECTION.ANIMALS, {[cat]: initialValue, [dog]: {name: 'Rex'}});
expect(collectionCallback).toHaveBeenNthCalledWith(1, {[cat]: initialValue}, ONYX_KEYS.COLLECTION.ANIMALS);
expect(collectionCallback).toHaveBeenNthCalledWith(2, collectionDiff, ONYX_KEYS.COLLECTION.ANIMALS);

// Cat hasn't changed from its original value, expect only the initial connect callback
expect(catCallback).toHaveBeenCalledTimes(1);
Expand Down Expand Up @@ -1660,10 +1658,6 @@ describe('Onyx', () => {
},
},
ONYX_KEYS.COLLECTION.ROUTES,
{
[holidayRoute]: {waypoints: {0: 'Bed', 1: 'Home', 2: 'Beach', 3: 'Restaurant', 4: 'Home'}},
[routineRoute]: {waypoints: {0: 'Bed', 1: 'Home', 2: 'Work', 3: 'Gym'}},
},
);

connections.map((id) => Onyx.disconnect(id));
Expand Down Expand Up @@ -1734,7 +1728,6 @@ describe('Onyx', () => {
[cat]: {age: 3, sound: 'meow'},
},
ONYX_KEYS.COLLECTION.ANIMALS,
{[cat]: {age: 3, sound: 'meow'}},
);
expect(animalsCollectionCallback).toHaveBeenNthCalledWith(
2,
Expand All @@ -1743,7 +1736,6 @@ describe('Onyx', () => {
[dog]: {size: 'M', sound: 'woof'},
},
ONYX_KEYS.COLLECTION.ANIMALS,
{[dog]: {size: 'M', sound: 'woof'}},
);

expect(catCallback).toHaveBeenNthCalledWith(1, {age: 3, sound: 'meow'}, cat);
Expand All @@ -1755,7 +1747,6 @@ describe('Onyx', () => {
[lisa]: {age: 21, car: 'SUV'},
},
ONYX_KEYS.COLLECTION.PEOPLE,
{[bob]: {age: 25, car: 'sedan'}, [lisa]: {age: 21, car: 'SUV'}},
);

connections.map((id) => Onyx.disconnect(id));
Expand Down
5 changes: 2 additions & 3 deletions tests/unit/onyxUtilsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -553,11 +553,10 @@ describe('OnyxUtils', () => {
OnyxUtils.keysChanged(ONYXKEYS.COLLECTION.TEST_KEY, {[entryKey]: entryData}, {});

expect(collectionCallback).toHaveBeenCalledTimes(1);
// Collection subscriber receives the full cached collection, subscriber.key, and partial
const [receivedCollection, receivedKey, receivedPartial] = collectionCallback.mock.calls[0];
// Collection subscriber receives the full cached collection and subscriber.key
const [receivedCollection, receivedKey] = collectionCallback.mock.calls[0];
expect(receivedKey).toBe(ONYXKEYS.COLLECTION.TEST_KEY);
expect(receivedCollection[entryKey]).toEqual(entryData);
expect(receivedPartial).toEqual({[entryKey]: entryData});

Onyx.disconnect(connection);
});
Expand Down
Loading