-
Notifications
You must be signed in to change notification settings - Fork 1
/
lifecycle.js
69 lines (59 loc) · 2.17 KB
/
lifecycle.js
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
import { html, render } from "https://unpkg.com/lit-html";
import { withHooks, useProperties, useReducer, useEffect } from "../wchooks.js";
function ExampleLifeCycle() {
const [count, add] = useReducer(1, (count, increment) => count + increment);
const props = useProperties({ onLifeCycle: undefined });
// add a callback to be run just after the update to count has been rendered to the dom
useEffect(
// [!] the current DOM element is _always_ passed as first argument
// [!] notice that the dep array is spread as the last arguments of the lifecycle callback function
(count) => {
props.onLifeCycle(`useEffect ${count}.`);
return () => props.onLifeCycle(`useEffect ${count}. (cleared)`);
},
[count]
);
function removeHostFromDocument(target) {
target.getRootNode().host?.remove();
}
return html`
<fieldset>
<legend>
<b>useEffect</b>
</legend>
<button id="update" @click=${() => add(1)}>Force update</button>
<button id="remove" @click=${(e) => removeHostFromDocument(e.target)}>
Remove this block from document
</button>
<span>→ check lifecycle callbacks in the console</span>
<example-nested-life-cycle
.count=${count}
.onLifeCycle=${props.onLifeCycle}
></example-nested-life-cycle>
</fieldset>
`;
}
function ExampleNestedLifeCycle() {
const props = useProperties({ count: 0, onLifeCycle: undefined });
useEffect(
(count) => {
props.onLifeCycle(`child useEffect ${count}.`);
return () => props.onLifeCycle(`child useEffect ${count}. (cleared)`);
},
[props.count]
);
function removeHostFromDocument(target) {
target.getRootNode().host?.remove();
}
return html`
<fieldset style="margin-top: 8px">
<legend>nested element</legend>
<button @click=${(e) => removeHostFromDocument(e.target)}>
Remove this element from its parent
</button>
<span>→ compare the lifecycle order with the parent</span>
</fieldset>
`;
}
customElements.define("example-life-cycle", withHooks(ExampleLifeCycle, render));
customElements.define("example-nested-life-cycle", withHooks(ExampleNestedLifeCycle, render));