T
TanStack2w ago
wee-brown

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);
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);
// 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);
2 Replies
optimistic-gold
optimistic-gold2w ago
that's because $postId is a parent of $postId.comments, so it renders your $postId should instead be $postId.index.tsx same with $postId.comments vs $postId.comments.$commentId, $postId.comments -> $postId.comments.index the .index makes it so that a route cannot be a parent of any other route and thus never match routes with similar subsections
wee-brown
wee-brownOP2w ago
it worked perfectly

Did you find this page helpful?