पाठ 10 / 25
{#if}, {#each} and {#await}
Conditionals, keyed lists and promises.
Logic blocks
{#if cond}...{:else if other}...{:else}...{/if} renders conditionally. {#each list as item, i (item.id)}...{:else}...{/each} renders lists; the expression in parentheses is a key that lets Svelte move, insert and remove the correct DOM nodes when the list changes, instead of updating by index. Always key lists whose items can be reordered or removed and that contain stateful elements or components. {#await promise} shows a pending state, {:then value} the result and {:catch error} the failure. {#key expr} destroys and recreates its content when the value changes, which is handy for replaying transitions.
Markup that reacts
Logic blocks, element bindings, actions and transitions describe dynamic UI declaratively.
All three blocks together
A user list loaded from an API.
<script lang="ts">
type User = { id: number; name: string; active: boolean };
async function loadUsers(): Promise<User[]> {
const res = await fetch('/api/users');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
let usersPromise = $state(loadUsers());
</script>
{#await usersPromise}
<p>Loading...</p>
{:then users}
<ul>
{#each users as user (user.id)}
<li>
{user.name}
{#if !user.active}<em>(inactive)</em>{/if}
</li>
{:else}
<li>No users yet</li>
{/each}
</ul>
{:catch error}
<p role="alert">Could not load users: {error.message}</p>
{/await}
<button onclick={() => (usersPromise = loadUsers())}>Reload</button>Keys must be stable and unique
Use a database id, not the array index; an index key gives the same reuse problems as no key when items move.
त्वरित जाँच: Why add (item.id) to an {#each} block?
- So Svelte can match DOM nodes to items when the list is reordered or changed
- To sort the list by id
- To make the list load faster from the server
- It is required syntax for every each block
Answer
So Svelte can match DOM nodes to items when the list is reordered or changed — Keys give list items identity.