I am currently utilizing the "app" router within NextJS and aiming to implement Dynamic Routes in order to dynamically generate pages for blog posts.
The issue I'm facing involves passing an Object to the dynamically created page, specifically a Post
object with attributes like
{id: number, title: string, likes: number}
. It seems that achieving this is not straightforward.
In the best-case scenario, if I have a route as /posts/[id]
, such as /posts/1
, then I can retrieve the value 1
inside the dynamically generated page by defining the type:
interface PostPageProps {
params: {
id: string;
};
}
and using it as follows:
export default async function PostPage({ params }: PostPageProps) {
// ...
// params.id can be accessed.
}
Nevertheless, it appears impossible to capture an entire custom Object, like a Post
object, on the dynamically created page.
Directory Layout
/app
- /components
- /posts
- /[id]
- page.tsx
- page.tsx
- favicon.ico
- globals.css
- layout.tsx
- page.tsx
./app/posts/page.tsx
"use client";
// ...
type Post = {
id: number;
title: string;
likes: number;
};
export default function Page() {
const [posts, setPosts] = useState<Post[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function fetchPosts() {
...
}
fetchPosts();
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>{error}</p>;
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<h1 className="text-3xl font-bold underline">
{posts.map((post) => (
<li key={post.id}>
<Link href={`/posts/${post.id}`} className="block">
{post.title}
</Link>
</li>
))}
</h1>
</main>
);
}
./app/posts/[id]/page.tsx
type Post = {
id: number;
title: string;
likes: number;
};
interface PostPageProps {
params: {
id: string;
};
}
export default async function PostPage({ params }: PostPageProps) {
const { id } = params;
console.warn(params);
return (
<div>
<h1>{id}</h1>
</div>
);
}
One potential method to access a specific page involves utilizing the id provided in PostPageProps
to filter out the particular post of interest after fetching the data (stored in a .json
file in /public
). However, this approach would require loading the entire json file and filtering it for a specific post each time a specific post page is accessed. This could impact performance negatively, prompting my exploration of loading all data at once in the "parent" page from which I can navigate to each post on the dynamically created page (route). This is the recommended approach when utilizing the App router in NextJS, note that this substitutes the use of getStaticProps
which isn't applicable in my scenario.
If there exists a more effective approach to tackle this, please share your insights.