Skip to content

Commit

Permalink
Bug fix when resolving cache (#25545)
Browse files Browse the repository at this point in the history
We must use the asynclocalstorage one if it's available.
  • Loading branch information
sebmarkbage authored and rickhanlonii committed Dec 3, 2022
1 parent 40f0320 commit 2ce7008
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
10 changes: 6 additions & 4 deletions packages/react-server/src/ReactFlightCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,23 @@ function resolveCache(): Map<Function, mixed> {

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<T>(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;
},
Expand Down
23 changes: 23 additions & 0 deletions packages/react/src/__tests__/ReactFetch-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ let React;
let ReactServerDOMServer;
let ReactServerDOMClient;
let use;
let cache;

describe('ReactFetch', () => {
beforeEach(() => {
Expand All @@ -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) {
Expand Down Expand Up @@ -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() {
Expand Down

0 comments on commit 2ce7008

Please sign in to comment.