From 4922d9f42e0e9b8bbc843f976a1dd8e7cf284e8d Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Sat, 16 Apr 2022 22:25:05 +0200 Subject: [PATCH 1/2] throw error when using suspense on the server side without fallback --- src/use-swr.ts | 16 +++++++++++++++- src/utils/env.ts | 3 ++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/use-swr.ts b/src/use-swr.ts index 0e78a6c1c..4aad0871c 100644 --- a/src/use-swr.ts +++ b/src/use-swr.ts @@ -1,7 +1,12 @@ import { useCallback, useRef, useDebugValue } from 'react' import { defaultConfig } from './utils/config' import { SWRGlobalState, GlobalState } from './utils/global-state' -import { IS_SERVER, rAF, useIsomorphicLayoutEffect } from './utils/env' +import { + IS_REACT_LEGACY, + IS_SERVER, + rAF, + useIsomorphicLayoutEffect +} from './utils/env' import { serialize } from './utils/serialize' import { isUndefined, @@ -542,6 +547,15 @@ export const useSWRHandler = ( // If there is no `error`, the `revalidation` promise needs to be thrown to // the suspense boundary. if (suspense && isUndefined(data) && key) { + // SWR should throw when trying to use Suspense on the server with React 18, + // without providing any initial data. See: + // https://github.com/vercel/swr/issues/1832 + if (!IS_REACT_LEGACY && IS_SERVER) { + throw new Error( + 'Fallback data is required to use suspense on the server side.' + ) + } + // Always update fetcher and config refs even with the Suspense mode. fetcherRef.current = fetcher configRef.current = config diff --git a/src/utils/env.ts b/src/utils/env.ts index d21534ac1..732e85447 100644 --- a/src/utils/env.ts +++ b/src/utils/env.ts @@ -1,6 +1,7 @@ -import { useEffect, useLayoutEffect } from 'react' +import React, { useEffect, useLayoutEffect } from 'react' import { hasRequestAnimationFrame, isWindowDefined } from './helper' +export const IS_REACT_LEGACY = !(React as any).useId export const IS_SERVER = !isWindowDefined || 'Deno' in window // Polyfill requestAnimationFrame From a4525fd3b205fb03ec65985ab716df1ad82de5a5 Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Tue, 19 Apr 2022 10:36:16 +0200 Subject: [PATCH 2/2] Update src/use-swr.ts --- src/use-swr.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/use-swr.ts b/src/use-swr.ts index 4aad0871c..1fd4b852d 100644 --- a/src/use-swr.ts +++ b/src/use-swr.ts @@ -552,7 +552,7 @@ export const useSWRHandler = ( // https://github.com/vercel/swr/issues/1832 if (!IS_REACT_LEGACY && IS_SERVER) { throw new Error( - 'Fallback data is required to use suspense on the server side.' + 'Fallback data is required when using suspense in SSR.' ) }