javascript / intermediate
Snippet
Sicheres asynchrones Datenladen in onMount
Die Verwendung von asynchronen Funktionen in onMount stellt sicher, dass API-Aufrufe erst erfolgen, wenn die Komponente im DOM ist, was Fehler beim SSR verhindert.
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
Erklärung
1
onMount(async () => { ... })
Definiert einen asynchronen Lifecycle-Hook für Logik nach dem Mounten.
2
profile = await response.json();
Aktualisiert den lokalen Zustand reaktiv, nachdem das Promise aufgelöst wurde.