Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Fetching Data from APIs | Working with Real Data
Introduction to Svelte

Fetching Data from APIs

Pyyhkäise näyttääksesi valikon

Modern frontend applications constantly work with external data. Applications often fetch products, users, posts, weather information, or dashboard statistics from APIs instead of hardcoding content directly into the interface.

In this chapter, you will learn how to fetch real API data inside a Svelte application.

What Is an API?

An API allows applications to communicate and exchange data.

Frontend applications commonly use APIs to:

  • Load products;
  • Fetch user information;
  • Display search results;
  • Retrieve dynamic content.

Most modern frontend applications rely heavily on APIs.

Fetching Data with fetch()

Svelte applications can use JavaScript's built-in fetch() function to request external data.

Open App.svelte and add the following code:

<script>
  let users = [];

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

    users = await response.json();
  }

  loadUsers();
</script>

The fetch() function sends a request to the API and returns the response data.

Displaying API Data

Now render the users inside the interface:

<h1>Users</h1>

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

When the data finishes loading, Svelte updates the interface automatically.

Understanding Async Data

Fetching data takes time because the application communicates with an external server.

This process is asynchronous, which means the application continues running while waiting for the response.

The async and await keywords help make asynchronous code easier to read and manage.

APIs in Real Applications

Fetching API data is one of the most common frontend development tasks.

Applications frequently load:

  • Products;
  • Movies;
  • Chat messages;
  • Notifications;
  • Dashboard statistics;
  • Search results.

Modern frontend applications are heavily data-driven.

question mark

What is the recommended way to fetch API data in a Svelte component

Valitse oikea vastaus

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 5. Luku 1

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 5. Luku 1
some-alt