HOW TO CONSUME A RESTFUL API IN SVELTE

manyeya

Khutso siema

Posted on October 18, 2019

HOW TO CONSUME A RESTFUL API IN SVELTE

In this article i will share with you two techniques of consuming a rest api in svelte.

So basically, "consume an API" is just a fancy term for "use an API".
Disappointed? Don't be,You might learn something.

Method #1

The most common way to fetch data from other sources in svelte is to use the onMount lifecycle function.

here's an example from my last post


<script>
 import { onMount } from "svelte";

let myTodo;
  onMount(async()=>{
     const response = await fetch("https://jsonplaceholder.typicode.com/todos/1")
      const todo = await response.json();
      myTodo = todo
  });
</script>

<div>
  {#if myTodo}
    <ul>
      <li>{myTodo.title}</li>
    </ul>
  {:else}
    <p>loading.....</p>
  {/if}
</div>
Enter fullscreen mode Exit fullscreen mode

Let's say for some reason you don't want to fetch the data by using onMount lifecycle function,let's say for some reason you want to await the value of promises directly in your markup,well your in luck because svelte can do just that.
which brings me to

Method #2

<script>
 let myTodo = getTodo();

 async function getTodo() {
   const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
   const todo = await response.json();

   if (response.ok) {
     return todo;
   } else {
     throw new Error(todo);
   }
 }

</script>

{#await myTodo}
    <p>...waiting</p>
{:then todo_1}
    <p>{todo_1.title}</p>
{:catch error}
    <p style="color: red">{error.message}</p>
{/await}

Enter fullscreen mode Exit fullscreen mode

Hope this was helpful to someone out there!


Thanks for reading and stay tuned!

💖 💪 🙅 🚩
manyeya
Khutso siema

Posted on October 18, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related