0 day streak
javascript / beginner
Snippet

Fetching API Data on Mount using OnMount

The `onMount` lifecycle function runs once after the component first renders, making it ideal for performing asynchronous HTTP requests to populate state.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script>
import { onMount } from 'svelte';
let users = [];
onMount(async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
users = await res.json();
});
</script>
<ul>
{#each users as user}
<li>{user.name}</li>
{/each}
</ul>
svelte
Breakdown
1
onMount(async () => {
Registers an asynchronous lifecycle callback executed after component mount.
2
const res = await fetch('https://jsonplaceholder.typicode.com/users');
Sends an asynchronous network request to retrieve user data.
3
users = await res.json();
Parses JSON response data and assigns it to update the reactive list.