Search code examples
javascripttypescriptlit-elementlit

how can I set API data as inner html with lit


I have html element with lit

and I'm gonna set inner html of them with get request

how can set them?

import { LitElement, html, css } from "lit";
import { customElement } from "lit/decorators.js";
import axios from "axios";

@customElement("s-profile")
export class Profile extends LitElement {

  render() {
    return html`<p>${getProfile()}</p>`;
  }
}

// get data from api
async function getProfile(): Promise<string> {
  const username = window.location.pathname.replace("/", "");
  const result = await axios.get(
    `http://localhost:8000/api/getProfile?username=${username}`
  );
  const data: string = (<any>result).data.result.username;
  console.log(data);
  return data;
}


Solution

  • you can use updateRequest()

    import { LitElement, html, css } from "lit";
    import { customElement, property } from "lit/decorators.js";
    import axios from "axios";
    
    @customElement("s-profile")
    export class Profile extends LitElement {
    
      @property({ type: Object })
      data = {};
    
      // get user data from api
      async getProfile() {
        const username = window.location.pathname.replace("/", "");
        const result = await axios.get(
          `http://localhost:8000/api/getProfile?username=${username}`
        );
        const data: UserData = (<any>result).data.result;
        this.data = data;
        this.requestUpdate();
      }
    
      connectedCallback() {
        super.connectedCallback();
        this.getProfile();
      }
    
      render() {
        return html`<p>${this.data}</p>`;
      }
    }