diff --git a/packages/react-server/src/ReactFlightCache.js b/packages/react-server/src/ReactFlightCache.js index e69f84afb3704..20e5075118b6a 100644 --- a/packages/react-server/src/ReactFlightCache.js +++ b/packages/react-server/src/ReactFlightCache.js @@ -32,21 +32,23 @@ function resolveCache(): Map { export const DefaultCacheDispatcher: CacheDispatcher = { getCacheSignal(): AbortSignal { - let entry: AbortSignal | void = (resolveCache().get(createSignal): any); + const cache = resolveCache(); + let entry: AbortSignal | void = (cache.get(createSignal): any); if (entry === undefined) { entry = createSignal(); // $FlowFixMe[incompatible-use] found when upgrading Flow - currentCache.set(createSignal, entry); + cache.set(createSignal, entry); } return entry; }, getCacheForType(resourceType: () => T): T { - let entry: T | void = (resolveCache().get(resourceType): any); + const cache = resolveCache(); + let entry: T | void = (cache.get(resourceType): any); if (entry === undefined) { entry = resourceType(); // TODO: Warn if undefined? // $FlowFixMe[incompatible-use] found when upgrading Flow - currentCache.set(resourceType, entry); + cache.set(resourceType, entry); } return entry; }, diff --git a/packages/react/src/__tests__/ReactFetch-test.js b/packages/react/src/__tests__/ReactFetch-test.js index 24520c69d8cc5..38640033bb8fe 100644 --- a/packages/react/src/__tests__/ReactFetch-test.js +++ b/packages/react/src/__tests__/ReactFetch-test.js @@ -36,6 +36,7 @@ let React; let ReactServerDOMServer; let ReactServerDOMClient; let use; +let cache; describe('ReactFetch', () => { beforeEach(() => { @@ -50,6 +51,7 @@ describe('ReactFetch', () => { ReactServerDOMServer = require('react-server-dom-webpack/server.browser'); ReactServerDOMClient = require('react-server-dom-webpack/client'); use = React.experimental_use; + cache = React.experimental_cache; }); async function render(Component) { @@ -96,6 +98,27 @@ describe('ReactFetch', () => { expect(fetchCount).toBe(2); }); + // @gate enableFetchInstrumentation && enableCache + it('can dedupe cache in micro tasks', async () => { + const cached = cache(async () => { + fetchCount++; + return 'world'; + }); + async function getData() { + const r1 = await fetch('hello'); + const t1 = await r1.text(); + const t2 = await cached(); + return t1 + ' ' + t2; + } + function Component() { + return use(getData()); + } + expect(await render(Component)).toMatchInlineSnapshot( + `"GET hello [] world"`, + ); + expect(fetchCount).toBe(2); + }); + // @gate enableFetchInstrumentation && enableCache it('can dedupe fetches using Request and not', async () => { function Component() {