Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

breaking: Throw error when using suspense on the server side without fallback in React 18 #1931

Merged
merged 2 commits into from Apr 19, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 15 additions & 1 deletion 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,
Expand Down Expand Up @@ -542,6 +547,15 @@ export const useSWRHandler = <Data = any, Error = any>(
// 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) {
huozhi marked this conversation as resolved.
Show resolved Hide resolved
throw new Error(
'Fallback data is required to use suspense on the server side.'
shuding marked this conversation as resolved.
Show resolved Hide resolved
)
}

// Always update fetcher and config refs even with the Suspense mode.
fetcherRef.current = fetcher
configRef.current = config
Expand Down
3 changes: 2 additions & 1 deletion 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
Expand Down