diff --git a/lib/useOnyx.ts b/lib/useOnyx.ts index b5a5b9af6..f5929428c 100644 --- a/lib/useOnyx.ts +++ b/lib/useOnyx.ts @@ -72,11 +72,12 @@ type UseOnyxOptions = BaseUseOnyxOptions & U type FetchStatus = 'loading' | 'loaded'; -type ResultMetadata = { +type ResultMetadata = { status: FetchStatus; + sourceValue?: NonNullable | undefined; }; -type UseOnyxResult = [NonNullable | undefined, ResultMetadata]; +type UseOnyxResult = [NonNullable | undefined, ResultMetadata]; /** * Gets the cached value from the Onyx cache. If the key is a collection key, it will return all the values in the collection. @@ -158,6 +159,9 @@ function useOnyx>( // 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 | undefined>(undefined); + useEffect(() => { // These conditions will ensure we can only handle dynamic collection member keys from the same collection. if (options?.allowDynamicKey || previousKey === key) { @@ -284,7 +288,13 @@ function useOnyx>( // If the new value is `null` we default it to `undefined` to ensure the consumer gets a consistent result from the hook. const newStatus = newFetchStatus ?? 'loaded'; - resultRef.current = [previousValueRef.current ?? undefined, {status: newStatus}]; + resultRef.current = [ + previousValueRef.current ?? undefined, + { + status: newStatus, + sourceValue: sourceValueRef.current, + }, + ]; // If `canBeMissing` is set to `false` and the Onyx value of that key is not defined, // we log an alert so it can be acknowledged by the consumer. Additionally, we won't log alerts @@ -304,7 +314,7 @@ function useOnyx>( connectionRef.current = connectionManager.connect({ key, - callback: () => { + callback: (value, callbackKey, sourceValue) => { isConnectingRef.current = false; onStoreChangeFnRef.current = onStoreChange; @@ -315,6 +325,9 @@ function useOnyx>( // 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; + // Finally, we signal that the store changed, making `getSnapshot()` be called again. onStoreChange(); },