svelte

How To Fetch JSON In Svelte – Example


In this article, you will learn How To Fetch JSON In Svelte.

Fetching API

We will fetch sample API which is in JSON format and we will convert the fetch request to JSON and render it in our DOM.

<script>
  async function getUsers() {
    let response = await fetch("https://api.mocki.io/v1/7ce1d76a");
    let users = await response.json();
    return users;
  }
  const promise = getUsers();
</script>

In the above code, we have a <script> tag which contains an asynchronous function getUsers() as we will fetch the data from the internet, after converting it JSON we return the data and assign it to a variable promise.

Rendering In Our DOM

<div>
{#await promise}
	<p>Loading...</p>
{:then user}
	{#each user as user}
	<p>Name is {user.name}, ID: {user.id}</p>
	{/each}
{:catch error}
	<p style="color: red">{error.message}</p>
{/await}
</div>

In the above code, we are using await block which is provided by Svelte itself. We are awaiting the promise variable which we declared above, while the request is fetching we will show a Loading message to the user. And then we take the data which is being returned and loop through the array using each block provided by Svelte.

The Result of the above code


Share on social media

//