Currently, I am working on a mdx blog within the NextJS framework. To achieve this, I have implemented a function called getPostDataByCategory(category) in posts.js located under lib. This function is responsible for filtering posts based on categories.
getPostDataByCategory(category) {
const fileNames = fs.readdirSync(postsDirectory);
// allPostsData to read all the file contents parsed using gray-matter
const allPostsData = fileNames.map((fileName) => {
...
}
let filteredPosts = [];
filteredPosts.push(
allPostsData.filter((post) => post.categories.includes(category))
);
return { filteredPosts };
}
The filteredPosts data is obtained through getStaticProps within categories/[categories].js as shown below:
export async function getStaticProps({ params }) {
let posts = await getPostDataByCategory(params.categories);
const filteredPosts = JSON.parse(JSON.stringify(posts));
return {
props: {
filteredPosts,
},
};
}
Subsequently, the filteredPosts are received and displayed in a component named Category:
export default function Category({ filteredPosts }) {
return (
<Layout>
<ul>
{filteredPosts.map((posts) => (
<li key={posts.slug}>
<p>{posts.title}</p>
</li>
))}
</ul>
</Layout>
);
}
Unfortunately, an error occurs stating TypeError: filteredPosts.map is not a function
This error indicates that filteredPosts is not recognized as an array, requiring either object destructuring or conversion into an array.
I would greatly appreciate any assistance or insights. Thank you in advance.
I have extensively researched methods to convert an array of Objects into an array of arrays, but most solutions appear complex for my specific case. There has to be a simpler way to accomplish this task.