diff --git a/.changeset/olive-bananas-vanish.md b/.changeset/olive-bananas-vanish.md new file mode 100644 index 00000000000..646fc7d34a6 --- /dev/null +++ b/.changeset/olive-bananas-vanish.md @@ -0,0 +1,5 @@ +--- +"@apollo/client": patch +--- + +Passes `getServerSnapshot` to `useSyncExternalStore` so that it doesn't trigger a `Missing getServerSnapshot` error when using `useFragment_experimental` on the server. diff --git a/src/react/hooks/useFragment.ts b/src/react/hooks/useFragment.ts index 6b8d3165b53..c77923963b4 100644 --- a/src/react/hooks/useFragment.ts +++ b/src/react/hooks/useFragment.ts @@ -71,27 +71,30 @@ export function useFragment_experimental( const resultRef = useRef>(); let latestDiff = cache.diff(diffOptions); + // Used for both getSnapshot and getServerSnapshot + const getSnapshot = () => { + const latestDiffToResult = diffToResult(latestDiff); + return resultRef.current && + equal(resultRef.current.data, latestDiffToResult.data) + ? resultRef.current + : (resultRef.current = latestDiffToResult); + }; + return useSyncExternalStore( - forceUpdate => { + (forceUpdate) => { return cache.watch({ ...diffOptions, immediate: true, callback(diff) { if (!equal(diff, latestDiff)) { - resultRef.current = diffToResult(latestDiff = diff); + resultRef.current = diffToResult((latestDiff = diff)); forceUpdate(); } }, }); }, - - () => { - const latestDiffToResult = diffToResult(latestDiff); - return resultRef.current && - equal(resultRef.current.data, latestDiffToResult.data) - ? resultRef.current - : (resultRef.current = latestDiffToResult); - }, + getSnapshot, + getSnapshot ); }