Skip to content

Commit 2ce7008

Browse files
sebmarkbagerickhanlonii
authored andcommitted
Bug fix when resolving cache (#25545)
We must use the asynclocalstorage one if it's available.
1 parent 40f0320 commit 2ce7008

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

packages/react-server/src/ReactFlightCache.js

+6-4
Original file line numberDiff line numberDiff line change
@@ -32,21 +32,23 @@ function resolveCache(): Map<Function, mixed> {
3232

3333
export const DefaultCacheDispatcher: CacheDispatcher = {
3434
getCacheSignal(): AbortSignal {
35-
let entry: AbortSignal | void = (resolveCache().get(createSignal): any);
35+
const cache = resolveCache();
36+
let entry: AbortSignal | void = (cache.get(createSignal): any);
3637
if (entry === undefined) {
3738
entry = createSignal();
3839
// $FlowFixMe[incompatible-use] found when upgrading Flow
39-
currentCache.set(createSignal, entry);
40+
cache.set(createSignal, entry);
4041
}
4142
return entry;
4243
},
4344
getCacheForType<T>(resourceType: () => T): T {
44-
let entry: T | void = (resolveCache().get(resourceType): any);
45+
const cache = resolveCache();
46+
let entry: T | void = (cache.get(resourceType): any);
4547
if (entry === undefined) {
4648
entry = resourceType();
4749
// TODO: Warn if undefined?
4850
// $FlowFixMe[incompatible-use] found when upgrading Flow
49-
currentCache.set(resourceType, entry);
51+
cache.set(resourceType, entry);
5052
}
5153
return entry;
5254
},

packages/react/src/__tests__/ReactFetch-test.js

+23
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ let React;
3636
let ReactServerDOMServer;
3737
let ReactServerDOMClient;
3838
let use;
39+
let cache;
3940

4041
describe('ReactFetch', () => {
4142
beforeEach(() => {
@@ -50,6 +51,7 @@ describe('ReactFetch', () => {
5051
ReactServerDOMServer = require('react-server-dom-webpack/server.browser');
5152
ReactServerDOMClient = require('react-server-dom-webpack/client');
5253
use = React.experimental_use;
54+
cache = React.experimental_cache;
5355
});
5456

5557
async function render(Component) {
@@ -96,6 +98,27 @@ describe('ReactFetch', () => {
9698
expect(fetchCount).toBe(2);
9799
});
98100

101+
// @gate enableFetchInstrumentation && enableCache
102+
it('can dedupe cache in micro tasks', async () => {
103+
const cached = cache(async () => {
104+
fetchCount++;
105+
return 'world';
106+
});
107+
async function getData() {
108+
const r1 = await fetch('hello');
109+
const t1 = await r1.text();
110+
const t2 = await cached();
111+
return t1 + ' ' + t2;
112+
}
113+
function Component() {
114+
return use(getData());
115+
}
116+
expect(await render(Component)).toMatchInlineSnapshot(
117+
`"GET hello [] world"`,
118+
);
119+
expect(fetchCount).toBe(2);
120+
});
121+
99122
// @gate enableFetchInstrumentation && enableCache
100123
it('can dedupe fetches using Request and not', async () => {
101124
function Component() {

0 commit comments

Comments
 (0)