Skip to content

Commit

Permalink
breaking: Throw error when using suspense on the server side without …
Browse files Browse the repository at this point in the history
…fallback in React 18 (#1931)
  • Loading branch information
shuding committed Apr 19, 2022
1 parent 2dda58a commit dc78549
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
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) {
throw new Error(
'Fallback data is required when using suspense in SSR.'
)
}

// 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

0 comments on commit dc78549

Please sign in to comment.