Reputation: 109
I'm getting the following error in my Next.js app:
Error: Error serializing `.posts[0]` returned from `getStaticProps` in "/blog". Reason: `object` ("[object Promise]") cannot be serialized as JSON. Please only return JSON serializable data types.
I know there must be an issue resolving my promises somewhere, but I'm lost. Please help!
index.js
source code
export async function getStaticProps() {
const posts = await getSortedPosts()
return { props: { posts } }
}
posts.js
source code
export async function getSortedPosts() {
const fileNames = readdirSync(POSTS_DIR)
const allPostsData = fileNames.map(fileName => {
const slug = fileName.replace(/\.md$/, '')
return getPost(slug)
});
await Promise.all(allPostsData);
return allPostsData.sort((a, b) => (a.date < b.date ? 1 : -1))
}
export async function getPost(slug) {
const fullPath = path.join(POSTS_DIR, `${slug}.md`)
const fileContents = readFileSync(fullPath, 'utf8')
const { content, data: meta } = parseYaml(fileContents)
const contentHtml = await markdownToHtml(content)
return {
slug,
contentHtml,
...meta,
}
}
async function markdownToHtml(md) {
const processedContent = await remark()
.use(remarkHtml)
.process(md)
return processedContent.toString()
}
Upvotes: 3
Views: 2968
Reputation: 109
I was able to resolve the promise chain by assigning the result of Promise.all
and passing it along.
const promises = fileNames.splice(0, 2).map(fileName => {
const slug = fileName.replace(/\.md$/, '')
return getPost(slug)
});
const allPostsData = await Promise.all(promises); // Assign result of promise chain
Upvotes: 2