Skip to content

Commit

Permalink
🐛 fix(react-utils.ts): change type name from LazyImportType to NamedC…
Browse files Browse the repository at this point in the history
…omponents for better clarity and semantics

✨ feat(react-utils.ts): add error handling to throw an error if the requested component is not found in the module
  • Loading branch information
romantech committed Sep 15, 2023
1 parent a10ddca commit a2ed9cd
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/base/utils/react-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ComponentType, lazy } from 'react';

type ComponentName = string;
type Loader<T> = () => Promise<T>;
type LazyImportType = Record<ComponentName, unknown>;
type NamedComponents = Record<ComponentName, unknown>;

/**
* A utility function that enhances React.lazy() by allowing named imports. This function
Expand All @@ -14,12 +14,15 @@ type LazyImportType = Record<ComponentName, unknown>;
* @see {https://github.com/facebook/react/issues/14603#issuecomment-736878172 React's discussion on named imports}
* @see {https://github.com/JLarky/react-lazily/blob/main/src/core/lazily.ts react-lazily source code for a similar approach}
*/
export const lazyImport = <T extends LazyImportType>(loader: Loader<T>) => {
export const lazyImport = <T extends NamedComponents>(loader: Loader<T>) => {
return new Proxy({} as T, {
get: (_target, name: ComponentName) => {
return lazy(async () => {
const module = await loader();
return { default: module[name] as ComponentType<T> };
const Component = module[name] as ComponentType<T>;
if (!Component) throw new Error(`Component ${name} not found`);

return { default: Component };
});
},
});
Expand Down

0 comments on commit a2ed9cd

Please sign in to comment.