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

posts.$postId.tsx

55 lines1.5 KB

1import { createFileRoute } from '@tanstack/react-router'
2import * as React from 'react'
3import { ErrorComponent, useRouter } from '@tanstack/react-router'
4import {
5 useQueryErrorResetBoundary,
6 useSuspenseQuery,
7} from '@tanstack/react-query'
8import { PostNotFoundError } from '../posts'
9import { postQueryOptions } from '../postQueryOptions'
10import type { ErrorComponentProps } from '@tanstack/react-router'
11​
12export const Route = createFileRoute('/posts/$postId')({
13 loader: ({ context: { queryClient }, params: { postId } }) => {
14 return queryClient.ensureQueryData(postQueryOptions(postId))
15 },
16 errorComponent: PostErrorComponent,
17 component: PostComponent,
18})
19​
20export function PostErrorComponent({ error }: ErrorComponentProps) {
21 const router = useRouter()
22 if (error instanceof PostNotFoundError) {
23 return <div>{error.message}</div>
24 }
25 const queryErrorResetBoundary = useQueryErrorResetBoundary()
26​
27 React.useEffect(() => {
28 queryErrorResetBoundary.reset()
29 }, [queryErrorResetBoundary])
30​
31 return (
32 <div>
33 <button
34 onClick={() => {
35 router.invalidate()
36 }}
37 >
38 retry
39 </button>
40 <ErrorComponent error={error} />
41 </div>
42 )
44​
45function PostComponent() {
46 const postId = Route.useParams().postId
47 const { data: post } = useSuspenseQuery(postQueryOptions(postId))
48​
49 return (
50 <div className="space-y-2">
51 <h4 className="text-xl font-bold underline">{post.title}</h4>
52 <div className="text-sm">{post.body}</div>
53 </div>
54 )