0 day streak
javascript / beginner
Snippet

The onMount Lifecycle Hook

The onMount function schedules a callback to run as soon as the component has been rendered to the DOM. It is the preferred place to fetch data or interact with third-party libraries that need a DOM element.

snippet.js
javascript
1
2
3
4
5
6
7
8
import { onMount } from 'svelte';
let photos = [];
onMount(async () => {
const res = await fetch('https://api.example.com/photos');
photos = await res.json();
});
svelte
Breakdown
1
import { onMount } from 'svelte';
Imports the lifecycle hook from the Svelte core package.
2
onMount(async () => { ... });
Defines the code to run after the component is first mounted.