TanStackT
TanStack4mo ago
2 replies
brilliant-orange

Nested Path Params in React Router not working properly

I want to display all the comments of a given post and when I click in a comment it takes me to a page with $commentId: /posts/$postId/comments/$commentId
Right now I can only display the posts but I can't show their corresponding comments, let alone go to the commentId path
I have this file structure for now:
posts.route.tsx
posts.index.tsx
post.$postId.tsx
post.$postId.comments.tsx

console.log(comments);
never executes but the path changes in the address bar
// post.$postId.tsx
function PostComponent() {
    const postId = Route.useParams().postId;
    const { data: post } = useSuspenseQuery(postQueryOptions(postId));

    return (
        <div className="space-y-2">
            <h4 className="text-xl font-bold underline">{post.title}</h4>
            <div className="text-sm">{post.body}</div>
            <Link
                className="font-bold text-blue-500"
                params={{
                    postId: post.id,
                }}
                to={'/posts/$postId/comments'}
            >
                Show comments for post: {postId}
            </Link>
        </div>
    );
}
// post.$postId.comments.tsx
loader: ({ context: { queryClient }, params: { postId } }) => {
        return queryClient.ensureQueryData(commentsQueryOptions(postId));
    },

const { postId } = Route.useParams();
    const { data: comments } = useSuspenseQuery(commentsQueryOptions(postId));
console.log(comments);
Was this page helpful?