From 7f8091e627b6f49d90fe44c03f0a5ec5a71841bb Mon Sep 17 00:00:00 2001 From: Arya Emami Date: Fri, 31 May 2024 19:50:27 -0500 Subject: [PATCH] Fix usage of `useIsomorphicLayoutEffect` to mirror React-Redux --- .../toolkit/src/query/react/buildHooks.ts | 30 +++++++++++++++---- 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/packages/toolkit/src/query/react/buildHooks.ts b/packages/toolkit/src/query/react/buildHooks.ts index a6550452d2..02874bc1bc 100644 --- a/packages/toolkit/src/query/react/buildHooks.ts +++ b/packages/toolkit/src/query/react/buildHooks.ts @@ -53,12 +53,27 @@ import { useStableQueryArgs } from './useSerializedStableValue' import { useShallowStableValue } from './useShallowStableValue' // Copy-pasted from React-Redux +const canUseDOM = () => + !!( + typeof window !== 'undefined' && + typeof window.document !== 'undefined' && + typeof window.document.createElement !== 'undefined' + ) + +const isDOM = /* @__PURE__ */ canUseDOM() + +// Under React Native, we know that we always want to use useLayoutEffect + +const isRunningInReactNative = () => + typeof navigator !== 'undefined' && navigator.product === 'ReactNative' + +const isReactNative = /* @__PURE__ */ isRunningInReactNative() + +const getUseIsomorphicLayoutEffect = () => + isDOM || isReactNative ? useLayoutEffect : useEffect + export const useIsomorphicLayoutEffect = - typeof window !== 'undefined' && - !!window.document && - !!window.document.createElement - ? useLayoutEffect - : useEffect + /* @__PURE__ */ getUseIsomorphicLayoutEffect() export interface QueryHooks< Definition extends QueryDefinition, @@ -690,7 +705,10 @@ export function buildHooks({ // isFetching = true any time a request is in flight const isFetching = currentState.isLoading // isLoading = true only when loading while no data is present yet (initial load with no data in the cache) - const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching + const isLoading = + (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && + !hasData && + isFetching // isSuccess = true when data is present const isSuccess = currentState.isSuccess || (isFetching && hasData)