Skip to content

Commit 7cd0b95

Browse files
committed
[IMPL] lazy util
1 parent e2215c1 commit 7cd0b95

5 files changed

Lines changed: 24 additions & 4 deletions

File tree

apps/react-tools-demo/src/constants/components.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ export const COMPONENTS = [
134134
"isClient",
135135
"isAsync",
136136
"hotKeyHandler",
137-
"detectBrowser"
137+
"detectBrowser",
138+
"lazy"
138139
]
139140
] as const;

packages/react-tools/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@
137137
- [x] isAsync
138138
- [x] hotKeyHandler
139139
- [x] detectBrowser
140-
- [ ] lazy: lazy react-like customized
140+
- [x] lazy
141141
- [x] defaultSerializer
142142
- [x] getBase64
143143
- [x] removePropertiesFromArrayObjects

packages/react-tools/src/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,5 +221,6 @@ export {
221221
getObjectFromDottedString,
222222
mergeObjects,
223223
alphanumericCompare,
224-
changeStringCase
224+
changeStringCase,
225+
lazy
225226
} from './utils'

packages/react-tools/src/utils/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,5 @@ export { getKeyObjectFromValue } from './getKeyObjectFromValue';
1616
export { getObjectFromDottedString } from './getObjectFromDottedString';
1717
export { mergeObjects } from './mergeObjects';
1818
export { alphanumericCompare } from './alphanumericCompare';
19-
export { changeStringCase } from './changeStringCase';
19+
export { changeStringCase } from './changeStringCase';
20+
export { lazy } from './lazy';
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { lazy as legacy, ComponentType, LazyExoticComponent } from "react";
2+
3+
/**
4+
* **`lazy`**: Wrapper around _React.lazy_ with possibility to execute a function before and after component loading.
5+
* @param {() => Promise<{ default: T }>} load - function that returns a Promise or another thenable.
6+
* @param {()=> void} beforeLoad - function that will be executed before load component.
7+
* @param {()=> void} afterLoad - function that will be executed after load component.
8+
* @returns {LazyExoticComponent<T>} result - a React component you can render in your tree.
9+
*/
10+
export const lazy = <T extends ComponentType<unknown>>(load: () => Promise<{ default: T }>, beforeLoad?: () => void, afterLoad?: () => void): LazyExoticComponent<T> => {
11+
return legacy(() => {
12+
!!beforeLoad && beforeLoad();
13+
const promise = load();
14+
!!afterLoad && promise.then(() => afterLoad());
15+
return promise;
16+
})
17+
};

0 commit comments

Comments
 (0)