My scenario is , I have static data that is loaded in div, once after loaded I need to make ajax call and override the static data with new data, How to do the following in javascript
As I am newbie to lit-element, I dontknow how to do using callback function bit confused. once the div is loaded I need to make ajax call and override the static data with new data. I got stuck please help or any alternatives
import { LitElement, html, css } from 'https://unpkg.com/@polymer/lit-element/lit-element.js?module';
export class Example extends LitElement {
static get properties() {
return {
staticobj: {type: Object}
}
}
constructor() {
super();
this.static=[{
id: "value1",
country: "TH",
fee: 100
},{
id:"value2",
country: "SG",
fee: 200
}]
}
handleCall(id){
$.ajax({
url: "/en",
method: 'get',
global: false,
async: false,
data: {
value: id
},
success: function (data) {
callback(data, passData)
}
})
this.static=data; //override the static data
}
render(){
this.static.map((e)=>{
return html`
<div id="list">// call the ajax function once div loaded
<p>${e.id}</p>
<h6>${e.country}</h6>
<h5>${e.fee}</h5>
</div>
`
})
}
}
You should get into the ES6 and LitElement mind set. Forget JQuery and use fetch
(preferably with ES8 async/await
). Fetch your data in LitElement's firstUpdated()
. Then replace your array itself (the change won't be see if you replace the array elements themselves, because the change won't be rendered):
import { html, css, LitElement } from 'lit-element';
export default class FetchLit extends LitElement {
static get styles() {
return css`
:host {
display: block;
padding: 5px;
}
`;
}
static get properties() {
return {
users: { type: Array },
};
}
constructor() {
super();
this.users = [
{
firstName: 'Jane',
lastName: 'Doe',
email: 'jane.doe@somewhere.com',
},
];
}
// Don't use connectedCallback() since it can't be async
async firstUpdated() {
await fetch(`https://demo.vaadin.com/demo-data/1.0/people?count=10`)
.then(r => r.json())
.then(async data => {
this.users = data.result;
});
}
render() {
return html`
<ul>
${this.users.map(
u =>
html`
<li>${u.lastName}, ${u.firstName} - ${u.email}</li>
`,
)}
</ul>
`;
}
}
window.customElements.define('fetch-lit', FetchLit);
You can see this example at https://stackblitz.com/edit/fetch-lit