forked from preactjs/preact
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsuspense.jsx
97 lines (86 loc) · 1.72 KB
/
suspense.jsx
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// eslint-disable-next-line no-unused-vars
import {
createElement,
Component,
memo,
Fragment,
Suspense,
lazy
} from 'react';
function LazyComp() {
return <div>I'm (fake) lazy loaded</div>;
}
const Lazy = lazy(() => Promise.resolve({ default: LazyComp }));
function createSuspension(name, timeout, error) {
let done = false;
let prom;
return {
name,
timeout,
start: () => {
if (!prom) {
prom = new Promise((res, rej) => {
setTimeout(() => {
done = true;
if (error) {
rej(error);
} else {
res();
}
}, timeout);
});
}
return prom;
},
getPromise: () => prom,
isDone: () => done
};
}
function CustomSuspense({ isDone, start, timeout, name }) {
if (!isDone()) {
throw start();
}
return (
<div>
Hello from CustomSuspense {name}, loaded after {timeout / 1000}s
</div>
);
}
function init() {
return {
s1: createSuspension('1', 1000, null),
s2: createSuspension('2', 2000, null),
s3: createSuspension('3', 3000, null)
};
}
export default class DevtoolsDemo extends Component {
constructor(props) {
super(props);
this.state = init();
this.onRerun = this.onRerun.bind(this);
}
onRerun() {
this.setState(init());
}
render(props, state) {
return (
<div>
<h1>lazy()</h1>
<Suspense fallback={<div>Loading (fake) lazy loaded component...</div>}>
<Lazy />
</Suspense>
<h1>Suspense</h1>
<div>
<button onClick={this.onRerun}>Rerun</button>
</div>
<Suspense fallback={<div>Fallback 1</div>}>
<CustomSuspense {...state.s1} />
<Suspense fallback={<div>Fallback 2</div>}>
<CustomSuspense {...state.s2} />
<CustomSuspense {...state.s3} />
</Suspense>
</Suspense>
</div>
);
}
}