Looping through JSON object with Alpine JS in Lit 2.0 web component

Viewed 176

I can't figure out how to loop through the connections object from fetch using x-for and Alpine JS to display the 2 records.

I tried looping through ${this.connections} with x-for but got a "object Object" error.

import { LitElement, html } from "../lit-all.min.js";

export class ContentDiv extends LitElement {
    constructor() {
        super();
        this.connections;
    }

    static properties = {
        connections: {},
    };

    connectedCallback() {
        super.connectedCallback();

        const dbPath = sessionStorage.getItem("dbPath");

        fetch(`${dbPath}/connections/listConnections.php`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            }
        })
            .then((response) => {
                return response.json();
            })
            .then((response) => {
                this.connections = response;
            });
    }

    createRenderRoot() {
        return this;
    }

    render() {
        return html`
          <h1>Connections</h1>
          <div>
            <ul>
              ***Loop and display ${this.connections} here***
            </ul>
          </div>
        `;
    }
}

customElements.define("content-div", ContentDiv);
1 Answers

Is the the response coming as an array of objects? It seems like that based on your comment.

If so, I'd firstly instantiate this.connections as an empty array in the constructor:

    constructor() {
        super();
        this.connections = [];
    }

And within render, you can do one of multiple ways of rendering an array in the template.

For instance, with plain JavaScript array method.

    render() {
        return html`
          <h1>Connections</h1>
          <div>
            <ul>
              ${this.connections.map((item) => html`<li>${item.connectionName}</li>`)}
            </ul>
          </div>
        `;
    }

You may also use the map() built-in directive provided in the lit package.

import { LitElement, html, map } from "../lit-all.min.js";

...

    render() {
        return html`
          <h1>Connections</h1>
          <div>
            <ul>
              ${map(this.connections, (item) => html`<li>${item.connectionName}</li>`)}
            </ul>
          </div>
        `;
    }

See https://lit.dev/docs/templates/lists/ for more information.

Related