Chapter 10: Fetching Data with Svelte

Asynchronous data fetching requires explicit loading, error, and cancellation handling. Svelte pairs standard fetch calls with lifecycle hooks and reactive stores to keep UI state predictable.

Basic API Calls

Run client-side data fetches inside onMount so requests execute only in the browser after the component mounts. Remember that fetch() only rejects on network failures—HTTP 404 or 500 responses still resolve—so always check response.ok before parsing JSON, and pass an AbortController signal so unmounting cancels in-flight requests:

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

  let data = null;
  let error = null;

  onMount(() => {
    const controller = new AbortController();

    fetch('/api/summary', { signal: controller.signal })
      .then(res => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      })
      .then(json => { data = json; })
      .catch(err => {
        if (err.name !== 'AbortError') error = err.message;
      });

    return () => controller.abort();
  });
</script>

{#if error}
  <p class="error" role="alert">Error: {error}</p>
{:else if data}
  <p>Loaded {data.count} records.</p>
{:else}
  <p>Loading...</p>
{/if}

<style>
  .error { color: #f87171; }
</style>

Handling Loading and Error States

Separate loading, error, empty, and populated branches explicitly in your template. Using a try / catch / finally block guarantees loading resets to false even when a request fails, and keying the {#each} block by (item.id) preserves DOM state across refreshes:

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

  let loading = true;
  let items = [];
  let error = null;

  onMount(async () => {
    try {
      const response = await fetch('/api/posts');
      if (!response.ok) throw new Error(`Request failed (${response.status})`);
      items = await response.json();
    } catch (err) {
      error = err.message;
    } finally {
      loading = false;
    }
  });
</script>

{#if loading}
  <p>Loading posts...</p>
{:else if error}
  <div class="alert alert-danger" role="alert">{error}</div>
{:else if items.length === 0}
  <p>No posts found.</p>
{:else}
  <ul>
    {#each items as item (item.id)}
      <li>{item.title}</li>
    {/each}
  </ul>
{/if}

Working with Stores

When multiple components share fetched data—such as a notification list or user profile—move the fetch logic and state into a Svelte store (writable). Prefixing a store name with $ inside any .svelte component automatically subscribes to updates and unsubscribes on destroy:

// stores.js
import { writable } from 'svelte/store';

export const posts = writable([]);
export const loading = writable(false);
export const error = writable(null);

export async function loadPosts() {
  loading.set(true);
  error.set(null);
  try {
    const response = await fetch('/api/posts');
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    posts.set(await response.json());
  } catch (err) {
    error.set(err.message);
  } finally {
    loading.set(false);
  }
}

Components import the store and read $posts, $loading, and $error reactively without manual subscription boilerplate:

<script>
  import { onMount } from 'svelte';
  import { posts, loading, error, loadPosts } from './stores';

  onMount(loadPosts);
</script>

{#if $loading}
  <p>Loading...</p>
{:else if $error}
  <p class="error">{$error}</p>
{:else}
  <ul>
    {#each $posts as post (post.id)}
      <li>{post.title}</li>
    {/each}
  </ul>
{/if}

POST Requests

For mutations like creating or updating records, trigger fetch from an event handler rather than onMount, set the Content-Type: application/json header, and verify response.ok before updating local state:

<script>
  let title = '';
  let saving = false;

  async function addPost() {
    if (!title.trim() || saving) return;
    saving = true;
    try {
      const response = await fetch('/api/posts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: title.trim() })
      });
      if (!response.ok) throw new Error('Failed to create post');
      title = '';
    } finally {
      saving = false;
    }
  }
</script>

<input bind:value={title} placeholder="Post title" />
<button type="button" on:click={addPost} disabled={saving}>Add Post</button>

Practice: Create a shared posts store with loadPosts() and createPost(title) actions, handling HTTP errors, empty states, and in-flight button disabling.