Search code examples
ajaxfetchweb-componentlit-element

Fetching asynchronous data in a lit-element web component


I'm learning how to fetch asynchronous data in a web component using the fetch API and lit-element:

import {LitElement, html} from 'lit-element';

class WebIndex extends LitElement {

    connectedCallback() {
        super.connectedCallback();
        this.fetchData();

    }

    fetchData() {
        fetch('ajax_url')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                };
                response.json();
            })
            .then(data => {
                this.data = data;
                console.log('Success:', data);
            })
            .catch((error) => {
                console.error('Error:', error);
            });
    }

    render() {
        if (!this.data) {
            return html`
                <h4>Loading...</h4>
            `;
        }
        return html`
            <h4>Done</h4>
        `;
    }

}

customElements.define('web-index', WebIndex);

However the html rendered never changes. What I'm doing wrong? Is this the best way to fetch asynchronous data in a web component?


Solution

  • You need to register data in component properties so that the render is called once value of data is changed

    static get properties() {
       return {
         data: Object
       }
    }
    

    https://lit.dev/docs/components/properties/