Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: useOnyx returns new results when selector changes but store doesnt #601

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
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
7 changes: 7 additions & 0 deletions lib/useOnyx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(key: TKey
// Stores the newest cached value in order to compare with the previous one and optimize `getSnapshot()` execution.
const newValueRef = useRef<TReturnValue | undefined | null>(null);

const cachedValueRef = useRef<TReturnValue | undefined | null>(null);

// Stores the previously result returned by the hook, containing the data from cache and the fetch status.
// We initialize it to `undefined` and `loading` fetch status to simulate the initial result when the hook is loading from the cache.
// However, if `initWithStoredValues` is `false` we set the fetch status to `loaded` since we want to signal that data is ready.
Expand Down Expand Up @@ -199,11 +201,16 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(key: TKey
// If `newValueRef.current` is `null` or any other value it means that the cache does have a value for that key.
// This difference between `undefined` and other values is crucial and it's used to address the following
// conditions and use cases.

cachedValueRef.current = getCachedValue(key);

newValueRef.current = getCachedValue(key, selectorRef.current);

// We set this flag to `false` again since we don't want to get the newest cached value every time `getSnapshot()` is executed,
// and only when `Onyx.connect()` callback is fired.
shouldGetCachedValueRef.current = false;
} else if (selectorRef.current) {
resultRef.current[0] = selectorRef.current(cachedValueRef.current as OnyxValue<TKey>) ?? undefined;
}

const hasCacheForKey = OnyxCache.hasCacheForKey(key);
Expand Down
83 changes: 83 additions & 0 deletions tests/unit/useOnyxTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,89 @@
expect(result.current[0]).toBeUndefined();
expect(result.current[1].status).toEqual('loaded');
});

it('should return dynamic selected data from a collection key even if cache is the same', async () => {
const getEntriesByIDs = (ids: string[], data: Record<string, {id: string; name: string}>) =>
Object.fromEntries(Object.entries(data).filter(([, value]) => ids.includes(value.id)));

const generateSelector = (ids: string[]) => (entry: OnyxEntry<Record<string, {id: string; name: string}>>) => getEntriesByIDs(ids, entry ?? {});

const data = {
[`${ONYXKEYS.COLLECTION.TEST_KEY}entry1`]: {id: 'entry1_id', name: 'entry1_name'},
[`${ONYXKEYS.COLLECTION.TEST_KEY}entry2`]: {id: 'entry2_id', name: 'entry2_name'},
[`${ONYXKEYS.COLLECTION.TEST_KEY}entry3`]: {id: 'entry3_id', name: 'entry3_name'},
};

Onyx.mergeCollection(ONYXKEYS.COLLECTION.TEST_KEY, data as GenericCollection);

const {result, rerender} = renderHook(
({selector}) =>
useOnyx(ONYXKEYS.COLLECTION.TEST_KEY, {
// @ts-expect-error bypass
selector,
}),
{
initialProps: {
selector: generateSelector(['entry1_id', 'entry2_id']),
},
},
);

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

expect(result.current[0]).toMatchObject(getEntriesByIDs(['entry1_id', 'entry2_id'], data));

rerender({
selector: generateSelector(['entry3_id']),
});

expect(result.current[0]).toMatchObject(getEntriesByIDs(['entry3_id'], data));
});

it('should return dynamic selected data from a non-collection key even if cache is the same', async () => {
const getEntriesByIDs = (ids: string[], data: OnyxEntry<Record<string, {id: string; name: string}>>) =>
Object.fromEntries(Object.entries(data ?? {}).filter(([, value]) => ids.includes(value.id)));

const data = {
'0': {
id: '0',
name: 'test_name_0',
},
'1': {
id: '1',
name: 'test_name_1',
},
'2': {
id: '2',
name: 'test_name_2',
},
};

Onyx.set(ONYXKEYS.TEST_KEY, data);

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

const {result, rerender} = renderHook(
({ids}) => {
debugger;

Check failure on line 433 in tests/unit/useOnyxTest.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected 'debugger' statement
return useOnyx(ONYXKEYS.TEST_KEY, {
// @ts-expect-error bypass
selector: (entry: OnyxEntry<Record<string, {id: string; name: string}>>) => getEntriesByIDs(ids, entry),
});
},
{
initialProps: {
ids: ['0', '1'],
},
},
);

expect(result.current[0]).toMatchObject(getEntriesByIDs(['0', '1'], data));

rerender({ids: ['2']});

expect(result.current[0]).toMatchObject(getEntriesByIDs(['2'], data));
});
});

describe('initialValue', () => {
Expand Down
Loading