Fetching Data from APIs
Swipe um das Menü anzuzeigen
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.
Danke für Ihr Feedback!
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen