storybook/docs/snippets/svelte/document-screen-fetch.ts.mdx
2023-12-04 21:23:56 +00:00

48 lines
1.2 KiB
Plaintext

```html
<!-- YourPage.svelte -->
<script lang="ts">
import { onMount } from 'svelte';
import PageLayout from './PageLayout.svelte';
import DocumentHeader from './DocumentHeader.svelte';
import DocumentList from './DocumentList.svelte';
export let user: Record<string, unknown> = {};
export let document: Record<string, unknown> = {};
export let subdocuments: Record<string, unknown>[] = [];
export let status: 'error' | 'loading' | 'success' = 'loading';
onMount(async () => {
await fetch('https://your-restful-endpoint')
.then((res) => {
if (!res.ok) {
throw new Error(res.statusText);
}
return res;
})
.then((res) => res.json())
.then((data) => {
user = data.user;
status = 'success';
document = data.document;
subdocuments = data.subdocuments;
})
.catch(() => {
status = 'error';
});
});
</script>
{#if status === "error"}
<p>There was an error fetching the data!</p>
{:else if status === "loading"}
<p>Loading...</p>
{:else}
<PageLayout {user}>
<DocumentHeader {document} />
<DocumentList documents="{subdocuments}" />
</PageLayout>
{/if}
```