All posts

Fix Iterator Protocol Error in Svelte

Fix 'is not iterable' errors in Svelte components caused by iterating over non-array data in each blocks and reactive declarations.

Iterator Errors in Svelte

Svelte's {#each} block requires an iterable. When your data isn't what you expect — maybe it's undefined, a plain object, or a promise — you get a cryptic runtime error.

Typical Scenario

<script>
  let items; // undefined initially

  async function loadItems() {
    const res = await fetch('/api/items');
    items = await res.json();
  }

  loadItems();
</script>

<!-- ERROR: items is not iterable (it's undefined on first render) -->
{#each items as item}
  <p>{item.name}</p>
{/each}

The Fix

Initialize with an empty array or guard the each block:

<script>
  let items = []; // Safe default

  async function loadItems() {
    const res = await fetch('/api/items');
    items = await res.json();
  }

  loadItems();
</script>

{#each items as item}
  <p>{item.name}</p>
{/each}

Or use conditional rendering:

{#if items}
  {#each items as item}
    <p>{item.name}</p>
  {/each}
{:else}
  <p>Loading...</p>
{/if}

When the API Returns an Object

Sometimes your API wraps data in an object like { results: [...] }. Iterating over the wrapper fails:

<!-- Wrong -->
{#each data as item}

<!-- Right -->
{#each data.results as item}

Always validate the shape of API responses. Bugsly helps here by capturing the actual runtime error alongside the component stack, so you can see which {#each} block failed and what the value actually was at the time of the crash.

Try Bugsly Free

Track up to 100 issues per month on the free plan, with unlimited events and no credit card required.

Get Started Free