Sveltekit basic fetching?


25.07.2024, 22:56

die Fehlermeldung lautet: TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

1 Antwort

Das Problem liegt nicht im fetch-Request, sondern darin, wie du versuchst, die Daten weiterzugeben.

Ein sehr einfaches Beispiel kann zunächst so aussehen:

<script>
  import { onMount } from "svelte";

  let guides = [];

  onMount(async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts");

    if (response.ok) {
      guides = await response.json();
    }
  });
</script>

<div class="guides">
  <ul>
    {#each guides as guide}
      <li>{guide.title}</li>
    {/each}
  </ul>
</div>

Für die Verwendung von load-Funktionen lies zuerst in der Dokumentation, wie es funktioniert.

Beispielimplementation:

page.js

export async function load({ fetch }) {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts");

  if (response.ok) {
    const result = await response.json();
    return { guides };
  }

  /* otherwise do some error handling ... */
}

page.svelte

<script>
  export let data;
</script>

<div class="guides">
  <ul>
    {#each data.guides as guide}
      <li>{guide.title}</li>
    {/each}
  </ul>
</div>