1 | import './chunk/constants.js';
|
2 | import { i as isFunction } from './chunk/utils.js';
|
3 | import { useState, useEffect } from './core.js';
|
4 |
|
5 | let def = "default";
|
6 |
|
7 | let CaseLoading = () => ({ loading, ...props }) =>
|
8 | isFunction(loading) ? loading(props) : loading;
|
9 |
|
10 | let CaseError = () => ({ error = "", ...props }) =>
|
11 | isFunction(error) ? error(props) : error;
|
12 |
|
13 | let CaseEmpty = () => () => "";
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | function 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 |
|
56 | export { useLazy };
|
57 |
|