0
0
SvelteHow-ToBeginner · 4 min read

How to Use Fetch in Svelte: Simple Data Loading Guide

In Svelte, you use fetch inside a script tag to load data from APIs asynchronously. You typically call fetch inside lifecycle functions like onMount to get data when the component loads and update reactive variables to show the results.
📐

Syntax

Use fetch(url) to request data from a URL. It returns a promise that resolves to a response object. You then call response.json() to get the data as JSON.

In Svelte, use onMount to run fetch when the component appears. Store the data in a reactive variable to update the UI.

svelte
import { onMount } from 'svelte';

let data = null;
let error = null;

onMount(async () => {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    data = await response.json();
  } catch (err) {
    error = err.message;
  }
});
💻

Example

This example fetches a list of users from a public API when the component loads. It shows loading text while waiting, displays the user names when data arrives, and shows an error if fetching fails.

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

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

  onMount(async () => {
    try {
      const res = await fetch('https://jsonplaceholder.typicode.com/users');
      if (!res.ok) {
        throw new Error('Failed to fetch users');
      }
      users = await res.json();
    } catch (e) {
      error = e.message;
    } finally {
      loading = false;
    }
  });
</script>

{#if loading}
  <p>Loading users...</p>
{:else if error}
  <p>Error: {error}</p>
{:else}
  <ul>
    {#each users as user}
      <li>{user.name}</li>
    {/each}
  </ul>
{/if}
Output
Loading users... (briefly) then a bulleted list of user names from the API
⚠️

Common Pitfalls

Not handling errors: Always check response.ok before parsing JSON to catch HTTP errors.

Not using onMount: Calling fetch directly in the script runs it too early, before the component is ready.

Not updating reactive variables: Assign fetched data to variables declared with let so Svelte updates the UI.

svelte
/* Wrong way: fetch outside onMount, no error check */
<script>
  let data;
  fetch('https://api.example.com/data')
    .then(res => res.json())
    .then(json => data = json);
</script>

/* Right way: fetch inside onMount with error handling */
<script>
  import { onMount } from 'svelte';
  let data = null;
  let error = null;

  onMount(async () => {
    try {
      const res = await fetch('https://api.example.com/data');
      if (!res.ok) throw new Error('Fetch failed');
      data = await res.json();
    } catch (e) {
      error = e.message;
    }
  });
</script>
📊

Quick Reference

  • Use onMount to run fetch when component loads.
  • Check response.ok before parsing JSON.
  • Use let variables to store data for reactivity.
  • Handle errors with try/catch to avoid silent failures.
  • Update UI conditionally based on loading, error, or data states.

Key Takeaways

Use fetch inside onMount to load data when the Svelte component appears.
Always check response.ok before parsing JSON to handle HTTP errors.
Store fetched data in let variables to trigger UI updates.
Handle errors with try/catch to show meaningful messages.
Use conditional blocks to show loading, error, or data states in the UI.