How to Use onMount for Data Fetching in Svelte
Use Svelte's
onMount function to run code after the component is first rendered, ideal for data fetching. Inside onMount, perform async fetch calls and update component state to display the data.Syntax
The onMount function is imported from svelte and accepts a callback that runs once when the component is mounted. This callback can be async for data fetching. You update reactive variables inside it to trigger UI updates.
import { onMount } from 'svelte';- imports the functiononMount(() => { ... })- callback runs after component mounts- Use
asyncinside the callback for fetching data
svelte
import { onMount } from 'svelte'; let data; onMount(async () => { const response = await fetch('https://api.example.com/data'); data = await response.json(); });
Example
This example fetches a list of users from a public API when the component loads and displays their names. It shows how onMount runs the fetch and updates the UI reactively.
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 = 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
<p>Loading users...</p> (initially), then a list of user names after fetch completes
Common Pitfalls
Common mistakes when using onMount for data fetching include:
- Not marking the callback
asyncwhen usingawait, causing errors. - Trying to fetch data outside
onMount, which runs too early or multiple times. - Not handling fetch errors, leading to silent failures.
- Mutating variables without reactivity, so UI does not update.
svelte
/* Wrong: missing async, no error handling */ onMount(() => { const res = fetch('https://api.example.com/data'); data = res.json(); // This is a Promise, not data }); /* Right: async with try/catch */ onMount(async () => { try { const res = await fetch('https://api.example.com/data'); data = await res.json(); } catch (e) { console.error('Fetch error', e); } });
Quick Reference
Remember these tips when using onMount for data fetching:
- Always import
onMountfromsvelte. - Use an
asynccallback to await fetch calls. - Update reactive variables inside
onMountto trigger UI updates. - Handle errors gracefully with try/catch.
onMountruns only once after the component appears in the DOM.
Key Takeaways
Use
onMount to run code once after the component loads, perfect for data fetching.Make the
onMount callback async to use await with fetch.Update reactive variables inside
onMount to automatically update the UI.Always handle fetch errors inside
onMount to avoid silent failures.onMount runs only once, so it’s ideal for initial data loading.