Gosmith
Gosmith

Reputation: 469

svelte returning invalid array length

I have an api that retrieves a collection from mongodb successfully. The console.log(posts) shows the expected array of post.

Iterating over the array with for {each} returns an error

Home.svelte:90 Uncaught (in promise) RangeError: Invalid array length

What have I missed? Why is a card for each post not returned?

Thanks for any help.

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

  const apiBaseUrl = "http://localhost:5100/api";

  onMount(async () => {
    const res = await fetch(apiBaseUrl + "/list");
    posts = await res.json();
    console.log(posts)
  });

</script>

<div class="row">
    {#each posts as post}
      <div class="col s6">
        <div class="card">
          <div class="card-content">
            <p class="card-title">{post.title}</p>
            <p>{post.body}</p>
          </div>
        </div>
      </div>
    {/each}
</div>

Upvotes: 1

Views: 1897

Answers (1)

Michael
Michael

Reputation: 2631

The issue is that you haven't defined posts when Svelte renders you component. Ase you API call is async posts will be undefined by the time the each block runs.

All you have to do is define posts somewhere in your main script block:

let posts = [] // <- an empty array

Then after fetching it will re-render with your API posts.

Here is a working demo in the REPL Note: I had to change your code slightly as the API I used had a different structure than your local one.

You can also look into #await which lets Svelte deal with async code. This isn't however suitable for all async problems. I use both approaches.

TIP: You don't need to wrap your onMount function call. Svelte will only fetch your posts once.

Upvotes: 3

Related Questions