-
Notifications
You must be signed in to change notification settings - Fork 2
/
lazy.ts
31 lines (26 loc) · 1.02 KB
/
lazy.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { ComponentType, LazyExoticComponent, lazy } from 'react';
import { log } from './log';
const RETRY_COUNT = 3;
export function lazyWithRetry<Component extends ComponentType<any>>(
loadModule: () => Promise<{ default: Component }>,
options: { prefetch?: boolean } = {}
): LazyExoticComponent<Component> {
if (options.prefetch) {
// Already load the module now, but only use it if the component is actually rendered
// Ignore promise rejections (instead of leaving them unhandled)
loadModule().catch((error) => {
log('Lazy Retry', `Failed to load module in prefetch ${error.message}`);
});
}
async function retry() {
for (let count = 1; count < RETRY_COUNT; count++) {
try {
return await loadModule();
} catch (error) {
log('Lazy Retry', `Failed to load component, retry ${count}: ${(error as Error)?.message}`);
}
}
return await loadModule();
}
return lazy(retry);
}