99
1010import type { CacheDispatcher } from 'react-reconciler/src/ReactInternalTypes' ;
1111
12+ import {
13+ supportsRequestStorage ,
14+ requestStorage ,
15+ } from './ReactFlightServerConfig' ;
16+
1217function createSignal ( ) : AbortSignal {
1318 return new AbortController ( ) . signal ;
1419}
1520
21+ function resolveCache ( ) : Map < Function , mixed > {
22+ if ( currentCache ) return currentCache ;
23+ if ( supportsRequestStorage ) {
24+ const cache = requestStorage . getStore ( ) ;
25+ if ( cache ) return cache ;
26+ }
27+ // Since we override the dispatcher all the time, we're effectively always
28+ // active and so to support cache() and fetch() outside of render, we yield
29+ // an empty Map.
30+ return new Map ( ) ;
31+ }
32+
1633export const DefaultCacheDispatcher : CacheDispatcher = {
1734 getCacheSignal ( ) : AbortSignal {
18- if ( ! currentCache ) {
19- throw new Error ( 'Reading the cache is only supported while rendering.' ) ;
20- }
21- let entry : AbortSignal | void = ( currentCache . get ( createSignal ) : any ) ;
35+ let entry : AbortSignal | void = ( resolveCache ( ) . get ( createSignal ) : any ) ;
2236 if ( entry === undefined ) {
2337 entry = createSignal ( ) ;
2438 // $FlowFixMe[incompatible-use] found when upgrading Flow
@@ -27,11 +41,7 @@ export const DefaultCacheDispatcher: CacheDispatcher = {
2741 return entry ;
2842 } ,
2943 getCacheForType < T > ( resourceType : ( ) = > T ) : T {
30- if ( ! currentCache ) {
31- throw new Error ( 'Reading the cache is only supported while rendering.' ) ;
32- }
33-
34- let entry : T | void = ( currentCache . get ( resourceType ) : any ) ;
44+ let entry : T | void = ( resolveCache ( ) . get ( resourceType ) : any ) ;
3545 if ( entry === undefined ) {
3646 entry = resourceType ( ) ;
3747 // TODO: Warn if undefined?
0 commit comments