@@ -13,6 +13,17 @@ import React from 'react';
1313/** What `React.lazy` takes: a dynamic import of a module whose `default` is the component. */
1414export type LazyWidgetLoader < C extends React . ComponentType < any > > = ( ) => Promise < { default : C } > ;
1515
16+ /**
17+ * The component {@link recoverableLazy} returns. `load()` resolves to the
18+ * loaded widget itself, through the same shared request a mount makes (and,
19+ * like a mount, asks again after a failure). It is the seam a caller that
20+ * needs the widget's own function, not an element of it, reads instead of
21+ * `React.lazy`'s private fields; hosts render the component and never need it.
22+ */
23+ export type RecoverableLazyComponent < C extends React . ComponentType < any > > = React . ComponentType <
24+ React . ComponentProps < C >
25+ > & { load ( ) : Promise < C > } ;
26+
1627/** One request for the chunk, shared by every mount that asks while it stands. */
1728interface LoadAttempt {
1829 readonly Lazy : React . ComponentType < any > ;
@@ -49,14 +60,24 @@ interface LoadAttempt {
4960 */
5061export function recoverableLazy < C extends React . ComponentType < any > > (
5162 loader : LazyWidgetLoader < C > ,
52- ) : React . ComponentType < React . ComponentProps < C > > {
63+ ) : RecoverableLazyComponent < C > {
5364 let current : LoadAttempt | undefined ;
65+ // The import in flight, shared by every attempt and by `load()`; forgotten
66+ // on failure, so whoever asks next imports again.
67+ let inflight : Promise < { default : C } > | undefined ;
68+ const importOnce = ( ) : Promise < { default : C } > => {
69+ inflight ??= loader ( ) . catch ( ( error : unknown ) => {
70+ inflight = undefined ;
71+ throw error ;
72+ } ) ;
73+ return inflight ;
74+ } ;
5475
5576 const currentAttempt = ( ) : LoadAttempt => {
5677 if ( ! current || current . retired ) {
5778 const attempt : { Lazy ?: React . ComponentType < any > ; retired : boolean } = { retired : false } ;
5879 attempt . Lazy = React . lazy < React . ComponentType < any > > ( ( ) =>
59- loader ( ) . then (
80+ importOnce ( ) . then (
6081 ( loaded ) => loaded ,
6182 ( error : unknown ) => ( { default : failedLoad ( attempt as LoadAttempt , error ) } ) ,
6283 ) ,
@@ -72,7 +93,9 @@ export function recoverableLazy<C extends React.ComponentType<any>>(
7293 const [ attempt ] = React . useState ( currentAttempt ) ;
7394 return React . createElement ( attempt . Lazy , props ) ;
7495 }
75- return RecoverableLazy ;
96+ return Object . assign ( RecoverableLazy , {
97+ load : ( ) : Promise < C > => importOnce ( ) . then ( ( loaded ) => loaded . default ) ,
98+ } ) ;
7699}
77100
78101/**
0 commit comments