Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
66
rated 0 times [  72] [ 6]  / answers: 1 / hits: 12334  / 4 Years ago, wed, april 8, 2020, 12:00:00
<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


More From » svelte

 Answers
4

Changing:



export let posts;



to



export let posts = [];



fixed the issue. Thanks to @Heretic Monkey


[#4220] Monday, April 6, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristopherw

Total Points: 173
Total Questions: 107
Total Answers: 98

Location: Lesotho
Member since Wed, Jun 2, 2021
3 Years ago
kristopherw questions
Thu, Jan 21, 21, 00:00, 3 Years ago
Thu, Aug 13, 20, 00:00, 4 Years ago
Thu, Apr 23, 20, 00:00, 4 Years ago
Sun, Nov 24, 19, 00:00, 5 Years ago
;