<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.
posts.length
in your template to see what it is. I wonder if you are running into an async issue. – Taalresponse.length
returns5
, but loggingposts.length
after it is exported returnsCannot read property 'length' of undefined
. – Urbainconsole.log(JSON.stringify(posts, null, 2))
instead. See weird array behaviour in javascript for more about what that "i" shows when you hover over it. – Malmo{#each}
in the template and you may get something different. I don't know svelte or ghost or sapper, but typically there's a way of telling the template that the array will be filled asynchronously. Maybe if you just didexport let posts = [];
? – Malmocatch
in the statement above. – Urbain