Bug fix when resolving cache (#25545)

We must use the asynclocalstorage one if it's available.
This commit is contained in:
Sebastian Markbåge 2022-10-23 14:12:47 -04:00 committed by Rick Hanlon
parent 40f03209b6
commit 2ce7008f9c
2 changed files with 29 additions and 4 deletions

View File

@ -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;
},

View File

@ -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() {