0
0
SvelteHow-ToBeginner · 3 min read

How to Call API in Svelte: Simple Fetch Example

In Svelte, you call an API using the fetch function inside the onMount lifecycle hook to load data when the component appears. Use async/await to handle the response and update component state with let variables.
📐

Syntax

Use the onMount function from svelte to run code when the component loads. Inside it, use fetch to call the API. Use async/await to wait for the response and convert it to JSON. Store the data in a let variable to update the UI.

  • onMount(() => { ... }): Runs code after component mounts.
  • fetch(url): Calls the API.
  • await response.json(): Parses JSON data.
  • let data: Holds API data for rendering.
svelte
import { onMount } from 'svelte';

let data = null;

onMount(async () => {
  const response = await fetch('API_URL');
  data = await response.json();
});
💻

Example

This example fetches a list of users from a public API and displays their names. It shows how to load data on component mount and update the UI reactively.

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

  let users = [];
  let error = null;

  onMount(async () => {
    try {
      const res = await fetch('https://jsonplaceholder.typicode.com/users');
      if (!res.ok) {
        throw new Error('Failed to fetch');
      }
      users = await res.json();
    } catch (e) {
      error = e.message;
    }
  });
</script>

{#if error}
  <p>Error: {error}</p>
{:else if users.length === 0}
  <p>Loading users...</p>
{:else}
  <ul>
    {#each users as user}
      <li>{user.name}</li>
    {/each}
  </ul>
{/if}
Output
<ul><li>Leanne Graham</li><li>Ervin Howell</li><li>Clementine Bauch</li><li>Patricia Lebsack</li><li>Chelsey Dietrich</li><li>Mrs. Dennis Schulist</li><li>Kurtis Weissnat</li><li>Nicholas Runolfsdottir V</li><li>Glenna Reichert</li><li>Clementina DuBuque</li></ul>
⚠️

Common Pitfalls

Common mistakes when calling APIs in Svelte include:

  • Not using onMount and calling fetch directly in the script, which runs before the component is ready.
  • Not handling errors, causing the app to fail silently.
  • Not awaiting the fetch or response.json(), leading to unresolved promises.
  • Mutating data without let, so Svelte does not update the UI.
svelte
/* Wrong way: fetch outside onMount and no await */
<script>
  let data;
  fetch('https://jsonplaceholder.typicode.com/users')
    .then(res => res.json())
    .then(json => data = json);
</script>

/* Right way: use onMount and async/await */
<script>
  import { onMount } from 'svelte';
  let data;
  onMount(async () => {
    const res = await fetch('https://jsonplaceholder.typicode.com/users');
    data = await res.json();
  });
</script>
📊

Quick Reference

Remember these tips when calling APIs in Svelte:

  • Use onMount to run API calls after component loads.
  • Always use async/await with fetch for cleaner code.
  • Handle errors with try/catch to avoid silent failures.
  • Use let variables to store data so UI updates reactively.
  • Show loading or error states for better user experience.

Key Takeaways

Use onMount to call APIs after the component appears.
Use async/await with fetch to get and parse data cleanly.
Store API data in let variables to update the UI reactively.
Always handle errors to prevent app crashes.
Show loading and error messages for better user feedback.