Loading and Error States
Desliza para mostrar el menú
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.
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla