Skip to content

Commit

Permalink
add computed keys to useOnyx
Browse files Browse the repository at this point in the history
  • Loading branch information
TMisiukiewicz committed Feb 5, 2025
1 parent ca4353e commit 16d7305
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions lib/useOnyx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,16 @@ function tryGetCachedValue<TKey extends OnyxKey>(key: TKey): OnyxValue<OnyxKey>
* Gets the value from cache and maps it with selector. It changes `null` to `undefined` for `useOnyx` compatibility.
*/
function getCachedValue<TKey extends OnyxKey, TValue>(key: TKey, selector?: UseOnyxSelector<TKey, TValue>) {
const value = tryGetCachedValue(key) as OnyxValue<TKey>;
let value: OnyxValue<TKey>;

// Handle computed keys
if (OnyxUtils.isComputedKey(key)) {
// @ts-ignore

Check failure on line 109 in lib/useOnyx.ts

View workflow job for this annotation

GitHub Actions / lint

Use "@ts-expect-error" instead of "@ts-ignore", as "@ts-ignore" will do nothing if the following line is error-free
const cacheKey = OnyxUtils.getComputedCacheKey(key);
value = tryGetCachedValue(cacheKey) as OnyxValue<TKey>;
} else {
value = tryGetCachedValue(key) as OnyxValue<TKey>;
}

const selectedValue = selector ? selector(value) : (value as TValue);

Expand Down Expand Up @@ -291,8 +300,12 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(
isConnectingRef.current = true;
onStoreChangeFnRef.current = onStoreChange;

// Handle computed keys by using their cache key for the connection
// @ts-ignore
const connectionKey = OnyxUtils.isComputedKey(key) ? OnyxUtils.getComputedCacheKey(key) : key;

connectionRef.current = connectionManager.connect<CollectionKeyBase>({
key,
key: connectionKey,
callback: () => {
isConnectingRef.current = false;
onStoreChangeFnRef.current = onStoreChange;
Expand All @@ -308,7 +321,7 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(
onStoreChange();
},
initWithStoredValues: options?.initWithStoredValues,
waitForCollectionCallback: OnyxUtils.isCollectionKey(key) as true,
waitForCollectionCallback: OnyxUtils.isCollectionKey(connectionKey) as true,
reuseConnection: options?.reuseConnection,
});

Expand Down

0 comments on commit 16d7305

Please sign in to comment.