Author -  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.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY