-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
113 lines (95 loc) · 4.04 KB
/
index.js
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/* eslint-disable react/prop-types */
import * as React from 'react';
const defaultErrorHandler = ({ name, error: { message } }) =>
`Unable to fetch module: ${name}.\nError: ${message}.`;
const defaultPlaceholder = () => null;
/**
* Dynamically load any react module(Component or an HOC)
*
* @example
* - Module loader function
* const loader = f => import(`./dynamic/${f}.js`);
* - Use dynamic module(Make sure to use it outside render method, else new component is rendered in each render)
* const RealComponent = DynamicImport({ name: 'realModuleName', loader }),
*
* @param {Object} options - Options passed to react dynamic import functions
* @param {Function} options.loader - function which takes module name and returns promise to resolve module
* @param {Boolean} [options.isHOC=false] - Is the module an HOC?
* @param {String} [options.name] - Dynamic module to be fetched(Mostly it will be part of the module file name),
* optional if loader returns same component every time
* @param {Component} [options.placeholder=defaultPlaceholder] - React component to be rendered until actual module is fetched
* (You can add UX improvements like adding small delay before showing
* loader inside your class/functional component)
* @param {Component} [options.errorHandler=defaultErrorHandler] - React component to be rendered if fetching actual module fails.
* This will receive `name` and `error` object as `props`
*/
const DynamicImportWrapper = ({
loader,
isHOC = false,
name,
placeholder: Placeholder = defaultPlaceholder,
errorHandler: ErrorHandler = defaultErrorHandler,
}) => {
if (!loader || (loader && typeof loader !== 'function')) {
throw new Error("'loader' is required and should be of type 'function'.");
}
function DynamicImport(props) {
const isMounted = React.useRef(false);
const [DynamicModule, setDynamicModule] = React.useState(null);
const [fetchError, setFetchError] = React.useState(null);
const { hocArgs, forwardedRef, ...rest } = props;
React.useEffect(() => {
isMounted.current = true;
const loaderPromise = loader(name);
if (
!loaderPromise ||
(loaderPromise && !(loaderPromise instanceof Promise))
) {
throw new Error(
`Expected 'loader' to return a 'Promise', but, it returned '${typeof loaderPromise}' instead.`,
);
}
// Async await increases the bundle size
loaderPromise
.then(mod => {
if (isMounted.current) {
const m = mod.default || mod;
// useState executes the function if functional component is passed
setDynamicModule({ component: isHOC ? m(...hocArgs) : m });
}
})
.catch(err => {
if (isMounted.current) {
setFetchError(err);
}
});
return () => {
isMounted.current = false;
};
}, [hocArgs]);
if (fetchError) {
return <ErrorHandler error={fetchError} name={name} />;
}
return DynamicModule ? (
<DynamicModule.component {...rest} ref={forwardedRef} />
) : (
<Placeholder name={name} />
);
}
DynamicImport.displayName = `DynamicImport${isHOC ? ':HOC' : ''}(${name ||
'Unknown'})`;
function DynamicImportFetcher(props, ref) {
return <DynamicImport {...props} forwardedRef={ref} />;
}
DynamicImportFetcher.displayName = 'DynamicImportFetcher';
const ComponentFetcher = React.forwardRef(DynamicImportFetcher);
const HOCFetcher = (...args) => {
function DynamicImportHOCFetcher(props, ref) {
return <DynamicImport {...props} forwardedRef={ref} hocArgs={args} />;
}
DynamicImportHOCFetcher.displayName = 'DynamicImportHOCFetcher';
return React.forwardRef(DynamicImportHOCFetcher);
};
return isHOC ? HOCFetcher : ComponentFetcher;
};
export default DynamicImportWrapper;