by Sai gowtham

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.

App.svelte
<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.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course