Iteration and Blocks

Loading concept...

🎭 Svelte’s Magic Loops: Each Blocks, Keys & Await

Imagine you have a box of crayons. Each crayon is different — red, blue, green. You want to show ALL your crayons to your friend. Do you show them one by one, saying the same thing each time? YES! That’s exactly what Each Blocks do in Svelte!


🖍️ The Crayon Box Analogy

Think of your data as a box of crayons.

  • Each crayon = one item in your list
  • The box = your array of items
  • Showing each crayon = looping through with {#each}

Svelte makes showing your crayons super easy!


1️⃣ Each Blocks — Show Every Item

The Big Idea: When you have a list (like crayons), {#each} helps you show every single one without writing the same code again and again.

Simple Example

<script>
  let colors = ['Red', 'Blue', 'Green'];
</script>

{#each colors as color}
  <p>🖍️ {color} crayon</p>
{/each}

What happens?

  • Svelte looks at your colors list
  • For each color, it creates a paragraph
  • You see: 🖍️ Red crayon, 🖍️ Blue crayon, 🖍️ Green crayon

💡 Think of it like this: “For EACH color in my box, show me that color!”


2️⃣ Each Block Index — Know Your Position

The Big Idea: Sometimes you need to know “Is this the 1st crayon? The 2nd?” The index tells you the position!

Adding Index

<script>
  let fruits = ['Apple', 'Banana', 'Cherry'];
</script>

{#each fruits as fruit, i}
  <p>{i + 1}. {fruit}</p>
{/each}

Output:

1. Apple
2. Banana
3. Cherry

🎯 Key Point: i starts at 0 (like counting from zero!). We add 1 to show 1, 2, 3 instead of 0, 1, 2.

Real-Life Use

Imagine a race with runners. The index tells you who came 1st, 2nd, 3rd!

{#each runners as runner, position}
  <div class="medal-{position}">
    #{position + 1}: {runner.name}
  </div>
{/each}

3️⃣ Each Block Key — Give Each Item a Name Tag

The Big Idea: Imagine your crayons can move around in the box. How does Svelte know which is which? Keys are like name tags for each crayon!

Why Keys Matter

Without keys, when your list changes, Svelte might get confused. It’s like shuffling crayons without labels — which one is which?

<script>
  let todos = [
    { id: 1, text: 'Learn Svelte' },
    { id: 2, text: 'Build an app' },
    { id: 3, text: 'Have fun' }
  ];
</script>

{#each todos as todo (todo.id)}
  <div>{todo.text}</div>
{/each}

🏷️ The (todo.id) part is the KEY! It’s the unique name tag.

When to Use Keys

graph TD A[List items can change?] -->|Yes| B[Use a KEY!] A -->|No, static list| C[Key is optional] B --> D[Pick something unique] D --> E[id, email, username]

Rule of Thumb:

  • Items can be added/removed? Use keys!
  • Items can be reordered? Use keys!
  • List never changes? Keys are optional.

4️⃣ Await Blocks — Wait for Presents!

The Big Idea: Sometimes you’re waiting for something — like waiting for a present in the mail. While waiting, you don’t know what’s inside yet!

Await blocks let you handle:

  • Waiting (loading)
  • Success (got the present!)
  • Failure (something went wrong)

The Three States

<script>
  let promise = fetch('/api/user')
    .then(r => r.json());
</script>

{#await promise}
  <p>⏳ Loading your data...</p>
{:then data}
  <p>✅ Hello, {data.name}!</p>
{:catch error}
  <p>❌ Oops! {error.message}</p>
{/await}

🎁 Like waiting for a gift:

  • Still on the way? “Loading…”
  • Arrived and opened? “Here’s your gift!”
  • Lost in mail? “Something went wrong!”

Shorter Version (Skip Loading)

If you don’t need a loading state:

{#await promise then data}
  <p>Welcome, {data.name}!</p>
{/await}

5️⃣ Key Blocks — Force a Fresh Start

The Big Idea: Sometimes you want to completely restart something when a value changes. Like restarting a video game when you pick a new character!

How Key Blocks Work

<script>
  let selectedUser = 1;
</script>

{#key selectedUser}
  <UserProfile id={selectedUser} />
{/key}

🔄 What happens? Every time selectedUser changes, the <UserProfile> component is completely destroyed and recreated. Fresh start!

When to Use Key Blocks

graph TD A[Value changes] --> B{Need fresh component?} B -->|Yes| C[Use #key block] B -->|No| D[Normal update is fine] C --> E[Component resets completely] E --> F[Animations restart] E --> G[Internal state clears]

Perfect for:

  • Restarting animations
  • Resetting form state
  • Forcing components to re-initialize

Example: Restart Animation

<script>
  let count = 0;
</script>

<button on:click={() => count++}>
  Restart Animation
</button>

{#key count}
  <div class="animate-bounce">
    🎈 I bounce from the start!
  </div>
{/key}

Every click = the balloon bounces from the beginning!


🎯 Quick Comparison

Block Purpose Example
{#each} Loop through list Show all items
{#each ... , i} Loop with position Numbered list
{#each ... (key)} Loop with identity Reorderable items
{#await} Handle promises API calls
{#key} Force recreation Reset animations

🚀 Put It All Together

Here’s a real example using everything:

<script>
  let selectedId = 1;

  async function loadPosts(userId) {
    const res = await fetch(`/api/${userId}/posts`);
    return res.json();
  }

  $: postsPromise = loadPosts(selectedId);
</script>

<!-- User selector -->
{#each users as user, index (user.id)}
  <button on:click={() => selectedId = user.id}>
    {index + 1}. {user.name}
  </button>
{/each}

<!-- Posts with fresh load on user change -->
{#key selectedId}
  {#await postsPromise}
    <p>⏳ Loading posts...</p>
  {:then posts}
    {#each posts as post (post.id)}
      <article>{post.title}</article>
    {/each}
  {:catch}
    <p>❌ Failed to load posts</p>
  {/await}
{/key}

What’s happening:

  1. Each with index & key — Show numbered user buttons
  2. Key block — Reset when user changes
  3. Await block — Handle loading state
  4. Nested each with key — Show posts with unique IDs

✨ Remember This!

Each = Show all items in a list Index = Know the position (0, 1, 2…) Key = Give items a unique ID Await = Wait for promises (loading/success/error) Key Block = Force a complete restart

You’ve got this! 🎉 Svelte’s blocks make handling lists and async data feel like magic!

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.