<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.
Changing:
export let posts;
to
export let posts = [];
fixed the issue. Thanks to @Heretic Monkey