How to Use Fetch in Svelte: Simple Data Loading Guide
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.
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.
<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}
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.
/* 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
onMountto run fetch when component loads. - Check
response.okbefore parsing JSON. - Use
letvariables to store data for reactivity. - Handle errors with try/catch to avoid silent failures.
- Update UI conditionally based on loading, error, or data states.