Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

posts.$postId.tsx

51 lines1.5 KB

1import { ErrorComponent, Link, createFileRoute } from '@tanstack/react-router'
2import { useSuspenseQuery } from '@tanstack/react-query'
3import { postQueryOptions } from '../utils/posts'
4import type { ErrorComponentProps } from '@tanstack/react-router'
5import { NotFound } from '~/components/NotFound'
6​
7export const Route = createFileRoute('/posts/$postId')({
8 loader: async ({ params: { postId }, context }) => {
9 const data = await context.queryClient.ensureQueryData(
10 postQueryOptions(postId),
11 )
12​
13 return {
14 title: data.title,
15 }
16 },
17 head: ({ loaderData }) => ({
18 meta: loaderData ? [{ title: loaderData.title }] : undefined,
19 }),
20 errorComponent: PostErrorComponent,
21 notFoundComponent: () => {
22 return <NotFound>Post not found</NotFound>
23 },
24 component: PostComponent,
25})
26​
27export function PostErrorComponent({ error }: ErrorComponentProps) {
28 return <ErrorComponent error={error} />
30​
31function PostComponent() {
32 const { postId } = Route.useParams()
33 const postQuery = useSuspenseQuery(postQueryOptions(postId))
34​
35 return (
36 <div className="space-y-2">
37 <h4 className="text-xl font-bold underline">{postQuery.data.title}</h4>
38 <div className="text-sm">{postQuery.data.body}</div>
39 <Link
40 to="/posts/$postId/deep"
41 params={{
42 postId: postQuery.data.id,
43 }}
44 activeProps={{ className: 'text-black font-bold' }}
45 className="inline-block py-1 text-blue-800 hover:text-blue-600"
46 >
47 Deep View
48 </Link>
49 </div>
50 )