Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Loading and Error States | Working with Real Data
Introduction to Svelte

Loading and Error States

Svep för att visa menyn

Fetching data from APIs is not always instant. Sometimes requests take time to complete, and sometimes they fail completely due to network or server problems.

Modern frontend applications need to handle these situations properly to provide a better user experience.

Why Loading States Matter

When data is being fetched, users should understand that the application is still working.

Without loading states, the interface may look broken or empty while waiting for the API response.

Frontend applications often display:

  • Loading messages;
  • Spinners;
  • Skeleton placeholders;
  • Progress indicators.

These elements help communicate application status to users.

Creating a Loading State

Open App.svelte and update the code:

<script>
  let users = [];
  let loading = true;

  async function loadUsers() {
    const response = await fetch(
      'https://jsonplaceholder.typicode.com/users'
    );

    users = await response.json();

    loading = false;
  }

  loadUsers();
</script>

The loading variable tracks whether the request is still in progress.

Displaying Loading Content

Use conditional rendering to display a loading message:

{#if loading}
  <p>Loading users...</p>
{:else}
  <ul>
    {#each users as user}
      <li>{user.name}</li>
    {/each}
  </ul>
{/if}

While the data is loading, the message appears automatically.

After the request finishes, the user list is displayed.

Handling Errors

API requests can sometimes fail. Applications should handle these situations gracefully.

Update the component:

<script>
  let users = [];
  let loading = true;
  let error = false;

  async function loadUsers() {
    try {
      const response = await fetch(
        'https://jsonplaceholder.typicode.com/users'
      );

      users = await response.json();
    } catch {
      error = true;
    }

    loading = false;
  }

  loadUsers();
</script>

The try...catch block helps detect request failures.

Displaying Error Messages

Now display an error message when something goes wrong:

{#if loading}
  <p>Loading users...</p>

{:else if error}
  <p>Failed to load users.</p>

{:else}
  <ul>
    {#each users as user}
      <li>{user.name}</li>
    {/each}
  </ul>
{/if}

This creates a much safer and more user-friendly interface.

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 5. Kapitel 2

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 5. Kapitel 2
some-alt