Process data from a JSON endpoint in a Svelte app

Here’s a simple Svelte app that fetches and displays a list of users from the JSONPlaceholder API:

  1. First, set up a new Svelte project if you haven’t already:
Bash
npx degit sveltejs/template svelte-json-example cd svelte-json-example npm install
  1. Replace the contents of App.svelte with the following:
Svelte
<script>
  import { onMount } from 'svelte';

  let users = [];
  let error = null;

  onMount(async () => {
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      users = await response.json();
    } catch (err) {
      error = err.message;
    }
  });
</script>

<style>
  .error {
    color: red;
  }
</style>

{#if error}
  <p class="error">{error}</p>
{:else if users.length === 0}
  <p>Loading...</p>
{:else}
  <ul>
    {#each users as user}
      <li>{user.name} ({user.email})</li>
    {/each}
  </ul>
{/if}
  1. Now, run the app:
Bash
npm run dev

You should see a list of users displayed in your browser. If there’s an error while fetching the data, an error message will be shown.

What’s happening here?

  • We use Svelte’s onMount lifecycle function to run code when the component is first inserted into the DOM.
  • We use the fetch function to get the JSON data from the endpoint.
  • If the request is successful, we update the users array with the received data.
  • If there’s an error during the request, we catch it and update the error variable.
  • The markup then conditionally renders based on the state of users and error.

This is a basic example, and in a real-world scenario, you might also want to add retry logic, caching, etc.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top