Is there a way to assign API data as inner HTML using Lit?

Need help setting inner html of html elements with a get request

Any suggestions on how to achieve this?

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>`;
  }
}

// fetch 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;
}

Answer №1

Try utilizing the updateRequest() method.

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 = {};

  // Fetch user data from the 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>`;
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Selecting options in table is disrupted by filtering in ng-repeat

My table showcases selectable information, featuring parent rows and child rows. I am seeking a solution where only the parent rows are selectable if they have no children; otherwise, only the child rows should be clickable. Essentially, it's a selec ...

Exploring the proper syntax of the reduce() method in JavaScript

Here are two codes that can be executed from any browser. Code1: let prices = [1, 2, 3, 4, 5]; let result = prices.reduce( (x,y)=>{x+y} ); // Reduces data from x to y. console.log(result); Code2: let prices = [1, 2, 3, 4, 5]; let result = prices.red ...

Executing one controller function from another controller in Typescript

There are two typescript controllers in my project Controller A { public methodOfA() {//perform some action} } Controller B { public methodOfB() {//perform some action} } I am trying to implement the following functionality Controller B { ...

Could you provide insight into the reason behind debounce being used for this specific binding?

function debounce(fn, delay) { var timer return function () { var context = this var args = arguments clearTimeout(timer) timer = setTimeout(function () { fn.apply(context, args) }, delay) ...

Utilize an external JavaScript function within a React and TypeScript document

I have encountered an issue in my React/Next.js/TypeScript file where I am trying to load the YouTube iframe API in my useEffect hook. Here is the code snippet: useEffect(() => { const tag = document.createElement('script'); tag.src = ...

Having trouble getting jQuery click event to work with Express for loading a Handlebars page

My jQuery on click function is not working properly in conjunction with Express to route to a handlebars page and display the passed information. I have attempted different solutions such as changing the HTTP method from GET to POST, not using handlebars ...

What is the process for converting plain text into an image tag using the methods ".replace()" and ".html()"?

My goal is to customize this particular answer so that it can transform classic BCCode [img]{url}[/img] into an HTML image. In the code snippet provided, I have successfully implemented something similar with [b]text[/b]. However, when attempting to use [i ...

Does the React memo function modify the component's prop type?

I've come across a strange issue where defining two components causes compilation errors when written separately but not when written in the same file. test3.tsx import React from "react"; type ValueType = number[] | string[] | number | st ...

Guide on how to have two controllers execute identical tasks in Angular while modifying the appearance of the website

Trying to recreate Google's homepage functionality using Angular has been challenging for me. Despite watching Egghead videos and studying the API extensively, I couldn't find a specific example for this behavior. Here's what I aim to achiev ...

Enhancing user experience with jQuery tooltips

Having trouble adding a tooltip to a glyphicon. The JSFiddle example provided does not work for me as I am using jQuery to create the HTML elements like this: var trashIcon = $('<i>').addClass('glyphicon glyphicon-trash'); How ...

Guide on adding an additional key:value pair to a sub document in a MongoDB collection

I'm facing difficulties trying to add a new key:value pair to an existing object in a MongoDB document. I've experimented with $each, $push, and $addToSet, but it seems like those are intended for arrays. I then attempted $set, but that only upd ...

When converting an object into a specific type, the setter of the target type is not invoked

Imagine a scenario with a class structured like this: class Individual { private _name: string; get Name(): string { return this._name; } set Name(name: string) { this._name = name; } } Upon invoking HttpClient.get<Individual>(), it retrieve ...

Encountering an issue with npm start when attempting to launch the local host server for a React.js project

Encountering an issue with npm start Error message: 'Equipment' is not recognized as a command, operable program or batch file. internal/modules/cjs/loader.js:983 throw err; ^ Error: Module not found 'C:\Users\Home\Deskto ...

Issue with Abide Validation Events not triggering in Reveal Modal for Foundation Form

Currently, I am developing a login/registration feature for a basic web application using Foundation. On the index page, users are presented with a login screen and a register button. When the user clicks on the register button, a Reveal Modal pops up cont ...

What is the process for triggering an exception?

I have a specific function that converts a two-dimensional array into CSV format. The key requirement is that the function only supports text and numbers, triggering an error message for any other input types. Currently, when I execute the function, it s ...

Is there a way to flip a figure that is flipped upside down?

I'm currently working on creating a map using a json file to go from d3.js to Three.js. However, when the map is displayed, it appears upside down. I'm wondering if there is a way to flip it so that it displays correctly. As a newcomer to d3 and ...

Encountering an npm issue while attempting to execute the command "npx create-expo-app expoApp"

I've been attempting to set up an expo project, but npm is failing to do so. It does create necessary base files like APP.js, but nothing else. Here's the error I encountered: npm ERR! code ENOENT npm ERR! syscall lstat npm ERR! path C:\User ...

Guide on making a persistent sidebar using CSS and JavaScript

I'm in the process of developing a website that features a main content area and a sidebar, similar to what you see on Stack Overflow. The challenge I am facing is figuring out how to make the sidebar remain visible as a user scrolls down the page. T ...

Ways to release a client-side script with npm?

Within my nodejs package, I have included code that can be executed on both the backend and in a single .js file for browsers. In order to utilize the browser script, it must be placed within a script element in an HTML file. My query pertains to whether t ...

Displaying a two-dimensional array from a JSON file using AngularJS ng-repeat

Looking at this HTML file, I am trying to display a 2D array from the json-$scope.listOfIngredient <div class="ingredientMapping" ng-repeat="IngredientMapping in listOfIngredient track by $index"> <ul> <!-- BEGIN: Inner ngRep ...