I have a web component using Lit. The web component makes a web request using a similar approach as what’s in the documentation.
import {html, LitElement} from 'lit';
import {Task} from '@lit/task';
export class MyElement extends LitElement {
static properties = {
productId: {},
};
_fetchProductTask = new Task(this, {
task: async ([productId]) => {
const data = { Id: productId};
const dataString = JSON.stringify(JSON.stringify(data));
const response = await fetch(
`https://myApiEndpoint`,
{
method: 'POST',
header: {
'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, deflate, br',
'Content-Type': 'application/json',
'Connection': 'keep-alive'
},
body: dataString
});
if (!response.ok) { throw new Error(response); }
const result = await response.json();
return result;
},
args: () => [this.productId]
});
constructor() {
super();
this.productId= 1234;
}
render() {
return this._fetchProductTask.render({
pending: () => html `<p>Loading product ....</p>`,
complete: (response) => {
return html `
<h1>Product Info</h1>
<p>${response.ProductName}</p>
<pre>${JSON.stringify(response, null, 2)}</pre>
`},
error: (e) => html `<p>${e}</p>`
});
}
}
customElements.define('my-element', MyElement);
The above works as expected i.e. when the web component is placed on the web page, the web request is made and the product data is displayed as written in the render method. Issue is when the productId is changed (e.g. by changing the productId attribute on the web component tag using dev tools), this doesn’t trigger a new web request using the new productId.
What changes will I need to make to force product data to be fetched anew, using the new productId?