fbredius/storybook

View on GitHub
docs/snippets/svelte/document-screen-fetch.js.mdx

Summary

Maintainability
Test Coverage
```html
<!-- YourPage.svelte -->

<script>
  import { onMount } from 'svelte';

  import PageLayout from './PageLayout.svelte';
  import DocumentHeader from './DocumentHeader.svelte';
  import DocumentList from './DocumentList.svelte';
  export let user = {};
  export let document = {};
  export let subdocuments = [];
  export let status = '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>
{/if} 
{#if status === "loading"}
  <p>Loading...</p>
{:else}
  <PageLayout {user}>
    <DocumentHeader {document} />
    <DocumentList documents="{subdocuments}" />
  </PageLayout>
{/if}
```