UNPKG

1.55 kBJavaScriptView Raw
1import './chunk/constants.js';
2import { i as isFunction } from './chunk/utils.js';
3import { useState, useEffect } from './core.js';
4
5let def = "default";
6
7let CaseLoading = () => ({ loading, ...props }) =>
8 isFunction(loading) ? loading(props) : loading;
9
10let CaseError = () => ({ error = "", ...props }) =>
11 isFunction(error) ? error(props) : error;
12
13let CaseEmpty = () => () => "";
14
15/**
16 * It allows to load a component asynchronously.
17 * @param {Function} callback
18 * @param {object} [props]
19 *
20 * @todo add promise error detection behavior
21 */
22function useLazy(callback, args = [], msLoading = 100) {
23 let [Case, setCase] = useState(CaseEmpty);
24 useEffect(() => {
25 let cancel;
26 let ready;
27
28 callback()
29 .then(data => {
30 ready = true;
31 if (!cancel) {
32 let value = def in data ? data[def] : data;
33 setCase(() => props =>
34 isFunction(value) ? value(props) : value
35 );
36 }
37 })
38 .catch(() => {
39 ready = true;
40 if (!cancel) setCase(CaseError);
41 });
42
43 setTimeout(
44 () => (!cancel && !ready ? setCase(CaseLoading) : 0),
45 msLoading
46 );
47 return () => {
48 cancel = true;
49 if (ready) setCase(() => CaseEmpty);
50 };
51 }, args);
52
53 return Case;
54}
55
56export { useLazy };
57//# sourceMappingURL=use-lazy.js.map