storybook/docs/snippets/web-components/document-screen-fetch.js.mdx
2023-01-13 09:40:13 -07:00

64 lines
1.3 KiB
Plaintext

```js
// YourPage.js
import { LitElement, html } from 'lit-element';
class DocumentScreen extends LitElement {
static get properties() {
return {
_data: { type: Object },
_status: { state: true },
};
}
constructor() {
super();
this._status = 'idle';
}
connectedCallback() {
super.connectedCallback();
this.fetchData();
}
fetchData() {
this._status = 'loading';
fetch('https://your-restful-endpoint')
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
response.json();
})
.then((data) => {
this._status = 'success';
this._data = data;
})
.catch((error) => {
this._status = 'error';
});
}
render() {
if (this._status === 'error') {
return html`<p>There was an error fetching the data!</p>`;
}
if (this._status === 'loading') {
return html`<p>Loading...</p>`;
}
const { user, document, subdocuments } = this._data;
return html`
<demo-page-layout .user=${user}>
<demo-document-header .document=${document}></demo-document-header>
<demo-document-list .documents=${subdocuments}></demo-document-list>
</demo-page-layout>
`;
}
}
customElements.define('demo-document-screen', DocumentScreen);
```