0
0
SvelteHow-ToBeginner · 3 min read

How to Fetch Data in Svelte: Simple Guide with Examples

In Svelte, you fetch data using the fetch API inside lifecycle functions like onMount or reactive statements. Use async/await to handle the response and update component state for rendering.
📐

Syntax

To fetch data in Svelte, you typically use the fetch function inside the onMount lifecycle function. This ensures the fetch runs after the component is added to the page. You store the fetched data in a reactive variable to update the UI automatically.

  • onMount: Runs code after component loads.
  • fetch: Makes the network request.
  • Reactive variable: Holds data and triggers UI update.
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 error');
    data = await response.json();
  } catch (e) {
    error = e.message;
  }
});
💻

Example

This example fetches a list of users from a public API when the component loads. It shows loading, error, and data states in the UI.

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 (err) {
      error = err.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} ({user.email})</li>
    {/each}
  </ul>
{/if}
Output
Loading users... (initially) then a list of user names and emails or error message
⚠️

Common Pitfalls

Common mistakes when fetching data in Svelte include:

  • Not using onMount for fetch, causing fetch to run during server-side rendering or before component is ready.
  • Not handling fetch errors, which can break the UI.
  • Forgetting to await response.json(), leading to unresolved promises.
  • Not updating reactive variables properly, so UI does not refresh.
svelte
/* Wrong: fetch outside onMount, runs too early */
let data;
fetch('https://api.example.com/data')
  .then(res => res.json())
  .then(json => data = json);

/* Right: fetch inside onMount with async/await and error handling */
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;
  }
});
📊

Quick Reference

Tips for fetching data in Svelte:

  • Use onMount to run fetch after component loads.
  • Always handle errors with try/catch.
  • Use await for fetch and response.json().
  • Update reactive variables to trigger UI updates.
  • Show loading and error states for better UX.

Key Takeaways

Use the fetch API inside the onMount lifecycle function to load data after the component appears.
Always handle errors and loading states to keep the UI responsive and clear.
Update reactive variables with fetched data to automatically refresh the UI.
Avoid fetching data outside onMount to prevent issues with server-side rendering or premature calls.