Reputation: 9
I'm working on a blog in Nextjs, and I want it to to fetch all of the blog posts from a directory on build. But no matter what I return with getStaticProps, it always returns undefined in the main component. I have tried it in both next dev and next build.
//import Markdown from "react-markdown";
import styles from "./post.module.css";
import { promises as fs } from "fs";
import matter from "gray-matter";
const Post = ({ post, title, date, summary, image, test }) => {
console.log(post) //returns undefined
return (
<div id={ styles.postcontainer }>
<div id={ styles.post }>
</div>
</div>
);
};
export default Post;
export const getStaticPaths = async() => {
return {
paths: [...(await fs.readdir("assets/markdown")).map(file => { return { params: { id: file.replace(".md", "") } } }) ],
fallback: false
}
};
export const getStaticProps = async(context) => {
const post = await fs.readFile(`assets/markdown/${ context.params.id }.md`, "utf8");
console.log(post) //success
return {
props: {
post : matter(post).content,
title : matter(post).data.title,
date : matter(post).data.date,
summary : matter(post).data.summery,
image : `../assets/${ matter(post).data.image }`,
}
}
};
The markdown file looks like this
---
title : test
slug : test
date : 3-9-22
summery : some summery of the post...
image : test.png
---
# Header 1
Im pretty sure that the issue isn't with the data == undefined, because when I log it in terminal (inside getStaticProps) it responds with the correct values.
console.log(post)
---
title : test
slug : test
date : 3-9-22
summery : lorem ipsum
image : test.png
---
# Header 1
I've tried
props: {
test : "testvalue123"
}
but it still returns undefined in the main component. Thanks in advance!
Edit: The issue was with my _app.js file (not the code above). I had forgotten to add pageProps to the returned component in _app.js.
Upvotes: 0
Views: 977
Reputation: 2056
Try:
const post = await fs.readFile(`assets/markdown/${ context.params.id }.md`, "utf8");
const result = await post.json();
return {
props: {
post : result.content,
title : result.data.title,
date : result.data.date,
summary : result.data.summery,
image : `../assets/${ result.data.image }`,
}
}
Upvotes: 1