How to fetch data from an API in Svelte
In this tutorial, we are going to learn about how to fetch the data from a backend api in svelte using fetch api.
Fetching data from api
This a simple example that fetches the data from a JSON placeholder api once the data is available we are rendering it into the dom.
<script>
import { onMount } from "svelte";
let users = [];
onMount(async () => {
const res = await fetch(`https://jsonplaceholder.typicode.com/users`); users = await res.json(); });
</script>
<div>
<h1>Users List</h1>
{#each users as user}
<ul>
<li>{user.id} - {user.name}</li> <li>{user.email}</li> </ul>
{:else}
<!-- this block renders when users.length === 0 -->
<p>loading...</p>
{/each}
</div>
In the code above, we first declared a users
variable with an empty array []
, inside the onMount
lifecycle hook we are sending an HTTP get request to the Json placeholder
api once the response is available we assigning the data to the users
variable.
In Html, we are using the svelte each
block syntax to loop over the array of users and displaying each user details.
If the data is still fetching, we are displaying a loading
indicator using :else
block.