Fetch and iterate over data in Svelte

In this article, we will learn how to fetch and iterate over data in Svelte.

Fetch and iterate over data in Svelte

Svelte is the fairly new frontend framework but it takes the traditional approach of manipulating the original DOM, unlike using a virtual DOM as its peers do.

It comes with its own templating, which is easy to use but does require some learning.

All the component’s logic can be defined in a single file, we can define the functions under the script section and then invoke that function in the template to render the list based on the response data.

<script>
   async function fetchData(){
	const res = await fetch('https://jsonplaceholder.typicode.com/todos');
	const data = await res.json();
	return data;
   }
</script>

{#await fetchData()}
   <p>...Loading</p>
{:then todos}
   <ul>
	{#each todos as todo (todo.id)}
		<li>{todo.id}. {todo.title}</li>
	{/each}
   </ul>
{/await}

Also see Fetch and iterate over data in Vue.