I want to get some HTML elments from a webserver and render them in my web component with LitElement. My elements are saved as Strings in a MongoDB, an element is for example <div> do something</div>
.
I already get the elements with XMLHttpRequest but can not assign them to my property and render them.
import { LitElement, html } from 'lit-element';
class CassKomponent extends LitElement {
static get properties() {
return {
url: { type: String },
myArray: { type: Array },
};
}
constructor() {
super();
this.url = 'url';
this.myArray = [];
this.getResource;
}
render() {
return html`
<div id="check"></div>
<div>${this.url}</div>
<ul>
${this.myArray.map((i) => html`<li>${i}</li>`)}
</ul>
`;
}
getResource() {
var xhttp = new XMLHttpRequest();
xhttp.open('GET', this.url, true);
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
console.log(response);
//tried this one and it doesn't work
//document.querySelector('.heck').innerHTML = xhttp.responseText;
this.myArray = response;
}
};
xhttp.send();
}
}
customElements.define('cass-komponent', CassKomponent);
I have had changed it to fetch and it works somehow, tho I have no explanation for it. so my final solution looks like this.
render() {
return html `
<div id='placeholder'> </div>
`;
}
async getResource() {
fetch(this.url)
.then((response) => response.text())
.then((responseText) => {
this.myArray = JSON.parse(responseText);
this.shadowRoot.getElementById('placeholder').innerHTML = this.myArray;
})
.catch((error) => {
alert("The data could not be fetched");
console.error(error);
});
}