Search code examples
polymerlit-elementlit-html

How to share async method across the components - LitElement


I was trying to build a couple of components using lit-element where i have used async method which will be used to fetch the same data from an API.

Utility method:

async resolveData() {
    let response = await fetch('./emp-data.json');
    let empData = await response.json();
    let employees = null;

    employees = empData.employees;

    return employees;
}

Question: How can i actually separate this utility method from the components and just re-use it. Is there a best way to fix this in the context of lit-element?


Solution

  • You can create a separate services in order to serve a particular service across. Here is how:

    step 1: create a service file services.js

    export const litServices = (() => {
        const services = {}
        services.apiService1 = async () => {
            const response = await fetch('./emp-data.json').catch(err => {
                return {
                    data: {
                        isError: true
                    }
                }
            })
            return response.data;
        }
        return services;
    })();

    step 2: Import services into your component and call when needed

    import {
        html,
        LitElement
    } from 'litElements'
    import {
        litServices
    } from 'services'
    
    class comp extends LitElement {
        static get properties() {
            return {
    
            }
        }
        constructor() {
            super();
        }
        connectedCallback() {
            super.connectedCallback();
            this.receivedData = this._resolveData();
            this._formatResponse(this.receivedData)
        }
        async _resolveData() {
            const response = await litServices.apiService1();
            return response;
        }
        _formatResponse(receivedData) {
            console.log('First API response is: ', firstApiResponse);
        }
    }

    This will call the service when needed. This service can be reused across How to create services in litElement - sabarinath blog