-
Notifications
You must be signed in to change notification settings - Fork 0
/
lazy.ts
28 lines (25 loc) · 862 Bytes
/
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
import { useEffect, useState } from './hooks.js';
import { Component, SlotElem, component } from './elem.js';
export interface LazyConfig<T> {
import: () => Promise<{ default: Component<T> }>
fallback: SlotElem
}
type Lazy = {
(config: LazyConfig<void>): Component<void>
<T extends { [key: string]: any }>(config: LazyConfig<T>): Component<T>
};
export let lazy: Lazy = <T>(config: LazyConfig<T>): Component<T> => {
let comp: any = undefined;
return (props: any) => {
let [slot, setSlot] = useState({ val: comp ?? (() => config.fallback) });
useEffect(() => {
if (!comp) {
config.import().then(e => {
setSlot({ val: e.default });
comp = e.default;
});
}
}, []);
return component(slot.val, props);
};
};