Open History to see the last commit
1import ReactDOM from 'react-dom/client'
2import {
3 ErrorComponent,
4 Link,
5 Outlet,
6 RouterProvider,
7 createRootRoute,
8 createRoute,
9 createRouter,
10} from '@tanstack/react-router'
11import { TanStackRouterDevtools } from '@tanstack/router-devtools'
12import axios from 'redaxios'
13import type { ErrorComponentProps } from '@tanstack/react-router'
14β
15type PostType = {
16 id: string
17 title: string
18 body: string
19}
20β
21const fetchPosts = async () => {
22 console.info('Fetching posts...')
23 await new Promise((r) => setTimeout(r, 300))
24 return (
25 axios
26 /* eslint-disable-next-line ts/array-type */
27 .get<PostType[]>('https://jsonplaceholder.typicode.com/posts')
28 .then((r) => r.data.slice(0, 10))
29 )
30}
31β
32const fetchPost = async (postId: string) => {
33 console.info(`Fetching post with id ${postId}...`)
34 await new Promise((r) => setTimeout(r, 300))
35 const post = await axios
36 .get<PostType>(`https://jsonplaceholder.typicode.com/posts/${postId}`)
37 .catch((err) => {
38 if (err.status === 404) {
39 throw new NotFoundError(`Post with id "${postId}" not found!`)
40 }
41 throw err
42 })
43 .then((r) => r.data)
44β
45 return post
46}
47β
48const rootRoute = createRootRoute({
49 component: RootComponent,
50 notFoundComponent: () => {
51 return <p>This is the notFoundComponent configured on root route</p>
52 },
53})
54β
55function RootComponent() {
56 return (
57 <>
58 <div className="p-2 flex gap-2 text-lg border-b">
59 <Link
60 to="/"
61 activeProps={{
62 className: 'font-bold',
63 }}
64 activeOptions={{ exact: true }}
65 >
66 Home
67 </Link>{' '}
68 <Link
69 to={'/posts'}
70 activeProps={{
71 className: 'font-bold',
72 }}
73 >
74 Posts
75 </Link>{' '}
76 <Link
77 // @ts-expect-error
78 to="/this-route-does-not-exist"
79 activeProps={{
80 className: 'font-bold',
81 }}
82 >
83 This Route Does Not Exist
84 </Link>
85 </div>
86 <Outlet />
87 <TanStackRouterDevtools position="bottom-right" />
88 </>
89 )
90}
91const indexRoute = createRoute({
92 getParentRoute: () => rootRoute,
93 path: '/',
94 component: IndexComponent,
95})
96β
97function IndexComponent() {
98 return (
99 <div className="p-2">
100 <h3>Welcome Home!</h3>
101 </div>
102 )
103}
104β
105export const postsRoute = createRoute({
106 getParentRoute: () => rootRoute,
107 path: 'posts',
108 loader: () => fetchPosts(),
109}).lazy(() => import('./posts.lazy').then((d) => d.Route))
110β
111const postsIndexRoute = createRoute({
112 getParentRoute: () => postsRoute,
113 path: '/',
114 component: PostsIndexComponent,
115})
116β
117function PostsIndexComponent() {
118 return <div>Select a post.</div>
119}
120β
121class NotFoundError extends Error {}
122β
123const postRoute = createRoute({
124 getParentRoute: () => postsRoute,
125 path: '$postId',
126 errorComponent: PostErrorComponent,
127 loader: ({ params }) => fetchPost(params.postId),
128 component: PostComponent,
129})
130β
131function PostErrorComponent({ error }: ErrorComponentProps) {
132 if (error instanceof NotFoundError) {
133 return <div>{error.message}</div>
134 }
135β
136 return <ErrorComponent error={error} />
137}
138β
139function PostComponent() {
140 const post = postRoute.useLoaderData()
141β
142 return (
143 <div className="space-y-2">
144 <h4 className="text-xl font-bold">{post.title}</h4>
145 <hr className="opacity-20" />
146 <div className="text-sm">{post.body}</div>
147 </div>
148 )
149}
150β
151const routeTree = rootRoute.addChildren([
152 postsRoute.addChildren([postRoute, postsIndexRoute]),
153 indexRoute,
154])
155β
156// Set up a Router instance
157const router = createRouter({
158 routeTree,
159 defaultPreload: 'intent',
160 defaultStaleTime: 5000,
161})
162β
163// Register things for typesafety
164declare module '@tanstack/react-router' {
165 interface Register {
166 router: typeof router
167 }
168}
169β
170const rootElement = document.getElementById('app')!
171β
172if (!rootElement.innerHTML) {
173 const root = ReactDOM.createRoot(rootElement)
174β
175 root.render(<RouterProvider router={router} />)
176}