Skip to content
Draft
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
21 changes: 16 additions & 5 deletions lib/useOnyx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(
// explicit reset logic — eliminating the race condition where cleanup could clobber a boolean flag.
const connectedKeyRef = useRef<OnyxKey | null>(null);

// Tracks whether the hook has completed its initial mount subscription.
// Unlike connectedKeyRef (which gets nulled by cleanup), this persists across re-subscriptions.
const hasMountedRef = useRef(false);

// Indicates if the hook is connecting to an Onyx key.
const isConnectingRef = useRef(false);

Expand Down Expand Up @@ -264,12 +268,19 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(
(onStoreChange: () => void) => {
// Reset internal state so the hook properly transitions through loading
// for the new key instead of preserving stale state from the previous one.
previousValueRef.current = null;
newValueRef.current = null;
// Only reset when the key has actually changed (not on initial mount).
if (hasMountedRef.current) {
previousValueRef.current = null;
newValueRef.current = null;
sourceValueRef.current = undefined;
resultRef.current = [undefined, {status: options?.initWithStoredValues === false ? 'loaded' : 'loading'}];
}
// Force a cache re-read on every (re)subscription so any side effects from
// subscribeToKey (e.g. addNullishStorageKey for skippable collection member ids)
// are reflected in the next getSnapshot. Resetting this flag does not change
// resultRef by itself, so it doesn't cause an extra mount render.
shouldGetCachedValueRef.current = true;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are already setting shouldGetCachedValueRef.current = true; below, why do we need to set it again?

sourceValueRef.current = undefined;
resultRef.current = [undefined, {status: options?.initWithStoredValues === false ? 'loaded' : 'loading'}];

hasMountedRef.current = true;
isConnectingRef.current = true;
onStoreChangeFnRef.current = onStoreChange;

Expand Down
Loading