Search code examples
es6-promiselit-html

Rendering Array from a Promise using lit-html's until


I am trying to render some HTML using lit-html and their until syntax. I must confess, promises frustrate me, but I am a back-end developer by trade so this boils down to a lack of knowledge on my part. Any assistance would be greatly appreciated.

My Code

... removed for brevity ...

    async getCenters() {
        try {
            return await this.centerManager.allCenters;
        }
        catch (error) {
            return error;
        }
    }

    createView() {
        return html`
        <style>
            h2 {
                color: var(--ptsi-gold);
                font-family: 'Helvetica Neue Medium';
                font-size:1.4em;
            }

            p {
                font-family: 'Helvetica Neue Roman';
                font-size:1em;
            }

            .wrapper {
                display: flex;
                flex-wrap: wrap;
                justify-content: space-between;
            }

            .tile {
                background: var(--ptsi-gray);
                padding: 25px;
                margin: 25px 0px 25px 0px;
            }
        </style>
        <div class="wrapper">
            <div class="tile">
                <h2>This is a Hard Typed Title</h2>
                <p>This is a Hard Typed Body.</p>
            </div>
        </div>
        ${until(this.getCenters().then((data) => {
            data.forEach(element => {
                html`<div class="wrapper">
                        <div class="tile">
                            <h2>${element.program_code}</h2>
                            <p>${element.program_name}</p>
                        </div>
                    </div>
                `
            })
        }), html`<span>Loading...</span>`)
            }`
    }
}

... removed for brevity ...

When the page loads, I am looping through the array and I can inspect the values. Additionally, I see the Loading... while in the debugger, but the html`` never renders the content within the until() function.


Solution

  • The first argument to until is not resolving to any content. Update the functions to return values and use map instead of forEach.

    until(this.getCenters().then((data) => {
      return data.map(element => {
        return html`<div class="wrapper">
          <div class="tile">
            <h2>${element.program_code}</h2>
            <p>${element.program_name}</p>
          </div>
        </div>`
      })
    }), html`<span>Loading...</span>`)