Skip to content

Commit 70ee070

Browse files
authored
refactor: move customElements.whenDefined to willUpdate (#167)
1 parent f67919c commit 70ee070

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

packages/api-demo/src/layout.ts

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,8 @@ class ApiDemoLayout extends LitElement {
5757
@property({ attribute: false })
5858
propKnobs!: PropertyKnob[];
5959

60-
private _whenDefined: Record<string, Promise<unknown>> = {};
60+
@property({ type: Boolean })
61+
private defined = false;
6162

6263
private eventsController!: EventsController;
6364

@@ -72,16 +73,7 @@ class ApiDemoLayout extends LitElement {
7273
protected render(): TemplateResult {
7374
const { tag } = this;
7475

75-
// Invoke `requestUpdate` to render demo once the component is imported lazily
76-
// and becomes defined, but only it if matches the currently selected tag name.
77-
if (!customElements.get(tag)) {
78-
this._whenDefined[tag] = customElements.whenDefined(tag);
79-
this._whenDefined[tag].then(() => {
80-
if (this.tag === tag) {
81-
this.requestUpdate();
82-
}
83-
});
84-
76+
if (!this.defined) {
8577
return html`
8678
<div part="warning">
8779
Element ${tag} is not defined. Have you imported it?
@@ -190,6 +182,19 @@ class ApiDemoLayout extends LitElement {
190182
willUpdate(props: PropertyValues) {
191183
// Reset state if tag changed
192184
if (props.has('tag')) {
185+
const { tag } = this;
186+
this.defined = !!customElements.get(tag);
187+
188+
if (!this.defined) {
189+
// Change `defined` to render demo once the component is imported lazily
190+
// and becomes defined, but only if the corresponding tag is selected.
191+
customElements.whenDefined(tag).then(() => {
192+
if (this.tag === tag) {
193+
this.defined = true;
194+
}
195+
});
196+
}
197+
193198
this.knobs = {};
194199
this.propKnobs = getKnobs(this.tag, this.props, this.exclude);
195200
this.customKnobs = getCustomKnobs(this.tag, this.vid);

0 commit comments

Comments
 (0)