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>
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}
Hope this was helpful to someone out there!
Thanks for reading and stay tuned!
Top comments (4)
Greate article =)
Great article, there needs to me more tutorials about REST, thanks for adding one :]
Thank you for reading,will try my best to write more about REST
Thank you for the tutorial. How do you handle endpoints that require authentication e.g jwt ?