javascript / intermediate
Snippet
Safe Async Data Fetching in onMount
Using async functions within onMount ensures that API calls only happen after the component is in the DOM, preventing errors during Server-Side Rendering (SSR).
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script>import { onMount } from 'svelte';let profile = null;onMount(async () => {const response = await fetch('/api/user');if (response.ok) {profile = await response.json();}});</script>{#if profile}<p>Welcome, {profile.name}</p>{:else}<p>Loading...</p>{/if}
svelte
Breakdown
1
onMount(async () => { ... })
Defines an asynchronous lifecycle hook for post-mount logic.
2
profile = await response.json();
Updates the local state reactively after the promise resolves.