0 day streak
javascript / intermediate
Snippet

Initializing Logic with the onMount Hook

The onMount lifecycle hook runs after the component is first rendered to the DOM. It is the recommended place for side effects like API calls, setting up intervals, or interacting with third-party libraries that require DOM access.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
import { onMount } from 'svelte';
let photos = [];
onMount(async () => {
const res = await fetch('https://api.example.com/photos');
photos = await res.json();
});
</script>
<ul>
{#each photos as photo}
<li>{photo.title}</li>
{/each}</ul>
svelte
Breakdown
1
onMount(async () => { ... })
Defines a callback to run once the component is mounted.
2
photos = await res.json();
Updating the top-level variable triggers an automatic UI re-render.