The nested JSON file contains names of US states and corresponding cities.
City.json
[
{
"header": "Michigan ",
"id": "MI",
"PlaceList": [
{
"title": "Detroit",
"slug": "detroit"
},
{
"title": "Lansing ",
"slug": "lansing"
}
]
},
{
"header": "Iowa ",
"id": "IA",
"PlaceList": [
{
"title": "Ames",
"slug": "ames"
},
{
"title": "Davenport ",
"slug": "davenport"
}
]
}
]
The following code returns details of the cities stored in markdown file.
import React, { useMemo } from 'react'
import fs from "fs"
import Link from "next/link"
import Markdown from "react-markdown"
import rehypeRaw from "rehype-raw"
import matter from "gray-matter"
import City from '@/app/(posts)/Blog/City.json'
import path from "path"
import { Metadata, ResolvingMetadata } from "next"
const allPosts = City.flatMap(({ header, id, PlaceList }) =>
contentList.map((topics) => ({
stateName: header,
stateId: id,
...topics,
})),
);
// generates static pages
export async function generateStaticParams() {
return allPosts.map((post) => ({
chapterID: post.stateId,
postID: post.slug
}))
}
interface Post {
stateId: string;
title: string;
slug: string;
}
interface Pagination {
prev: string | null;
next: string | null;
post: Post | null;
switchState: boolean;
}
const BlogPage = ({params}:{params:any) => {
//gets post ids from matching slug
const postID = params.postID;
// calculate prev/next page slug and switch state
const { prev, next, post, switchState } = useMemo<Pagination>(() => {
const postIndex = allPosts.findIndex(({ slug }) => slug === postID);
if (postIndex === -1) {
return {
prev: null,
next: null,
post: null,
switchState: false
};
}
const currentPost = allPosts[postIndex];
const isLastPostInHeader =
postIndex === allPosts.length - 1 ||
allPosts[postIndex + 1]?.stateId !== currentPost.stateId;
return {
prev: allPosts[postIndex - 1]?.slug || null,
post: currentPost,
next: isLastPostInState ? null : allPosts[postIndex + 1]?.slug || null,
switchState: isLastPostInState
};
}, [postID]);
if(!post) {
return null;
}
const curr_post = GetPostContent(`${post.stateId}`,`${post.slug}`)
return (
<>
<h1>{curr_post.title}</h1>
<hr className="my-6 border border-dashed bg-sky-600 h-0.5" />
<article lang="bn" className="prose lg:prose-xl">
<Markdown rehypePlugins={[rehypeRaw]}>
{curr_post.content}</Markdown>
</article>
<Link
className="float-left text-teal-600"
aria-disabled={!prev}
href={prev ? `${prev}` : ''}
>
prev
</Link>
<Link
className="float-right text-teal-600"
aria-disabled={!next}
href={next ? `${next}` : ''}
>
next
</Link>
)}
</>
)
}
export default BlogPage
Is there a better way to parse data from JSON in NextJS?