Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: {#each} only iterates over array-like objects. -- Javascript & Svelte

<script context="module">
    import GhostContentAPI from '@tryghost/content-api';

    // const api = 'http://localhost/posts';
    const api = new GhostContentAPI({
        url: 'http://localhost',
        key: '95a0aadda51e5d621abd2ee326',
        version: "v3"
    });

    export async function preload({ params, query }) {
        try {
            const response = await api.posts.browse({ limit: 5, fields: 'title, slug' });
            return {
                posts: response
            }
        } catch(err) {
            console.log('Error');
        }
    }
</script>

<script>
    export let posts;
</script>

<svelte:head>
    <title>Blog</title>
</svelte:head>

<h1>Recent posts</h1>
<ul>
    {#each posts as post}
        <li>
            <a rel='prefetch' href='blog/{post.slug}'>{post.title}</a>
        </li>
    {/each}
</ul>

I'm using vanilla JavaScript and Svelte to simply fetch a list of blog posts, which are objects from the Ghost Blog Rest API. The Ghost API function works fine and pulls the correct objects, but the problem begins when trying to use Svelte's {#each} block to display each object because they aren't in an array and I cannot figure out how to fix it. Here's the exact error message in the console:

Error: {#each} only iterates over array-like objects.

Writing a console.log(response) after the const response declaration outputs the attached image, but only if I comment out the {#each} block first.

I'm guessing I simply need to move the 5 objects into an array, but I also don't understand why the console.log above only works when the HTML is commented out.

Console Log Image

like image 990
Joe Berthelot Avatar asked Apr 08 '20 16:04

Joe Berthelot


People also ask

What does it mean in error?

Definition of in error 1 : not correct : mistaken I believe your conclusion is in error. The judge was in error when she allowed the evidence to be admitted. 2 : in a way that is not correct My earlier statement was made in error.

What is the synonym of error?

Some common synonyms of error are blunder, lapse, mistake, and slip. While all these words mean "a departure from what is true, right, or proper," error suggests the existence of a standard or guide and a straying from the right course through failure to make effective use of this.

Whats the opposite of an error?

Antonyms. rightness correctness natural object overgarment better. incorrectness wrongness erroneousness.

What do you understand by error*?

An error is something you have done which is considered to be incorrect or wrong, or which should not have been done. NASA discovered a mathematical error in its calculations. [ + in]


1 Answers

Changing:

export let posts;

to

export let posts = [];

fixed the issue. Thanks to @Heretic Monkey

like image 97
Joe Berthelot Avatar answered Oct 15 '22 04:10

Joe Berthelot