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

main.tsx

269 lines6.3 KB

1import React from 'react'
2import ReactDOM from 'react-dom/client'
3import {
4 Await,
5 ErrorComponent,
6 Link,
7 MatchRoute,
8 Outlet,
9 RouterProvider,
10 createRootRoute,
11 createRoute,
12 createRouter,
13 defer,
14} from '@tanstack/react-router'
15import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
16import axios from 'redaxios'
17import type { ErrorComponentProps } from '@tanstack/react-router'
18import './styles.css'
19​
20type PostType = {
21 id: string
22 title: string
23 body: string
25​
26type CommentType = {
27 id: string
28 postId: string
29 name: string
30 email: string
31 body: string
33​
34const fetchPosts = async () => {
35 console.info('Fetching posts...')
36 await new Promise((r) => setTimeout(r, 100))
37 return axios
38 .get<Array<PostType>>('https://jsonplaceholder.typicode.com/posts')
39 .then((r) => r.data.slice(0, 10))
41​
42const fetchPost = async (postId: string) => {
43 console.info(`Fetching post with id ${postId}...`)
44​
45 const commentsPromise = new Promise((r) => setTimeout(r, 2000))
46 .then(() =>
47 axios.get<Array<CommentType>>(
48 `https://jsonplaceholder.typicode.com/comments?postId=${postId}`,
49 ),
50 )
51 .then((r) => r.data)
52​
53 const post = await new Promise((r) => setTimeout(r, 1000))
54 .then(() =>
55 axios.get<PostType>(
56 `https://jsonplaceholder.typicode.com/posts/${postId}`,
57 ),
58 )
59 .catch((err) => {
60 if (err.status === 404) {
61 throw new NotFoundError(`Post with id "${postId}" not found!`)
62 }
63 throw err
64 })
65 .then((r) => r.data)
66​
67 return {
68 post,
69 commentsPromise: defer(commentsPromise),
70 }
72​
73function Spinner({ show, wait }: { show?: boolean; wait?: `delay-${number}` }) {
74 return (
75 <div
76 className={`inline-block animate-spin px-3 transition ${
77 (show ?? true)
78 ? `opacity-1 duration-500 ${wait ?? 'delay-300'}`
79 : 'duration-500 opacity-0 delay-0'
80 }`}
81 >
82 β₯
83 </div>
84 )
86​
87const rootRoute = createRootRoute({
88 component: RootComponent,
89})
90​
91function RootComponent() {
92 return (
93 <>
94 <div className="p-2 flex gap-2 text-lg">
95 <Link
96 to="/"
97 activeProps={{
98 className: 'font-bold',
99 }}
100 activeOptions={{ exact: true }}
101 >
102 Home
103 </Link>{' '}
104 <Link
105 to="/posts"
106 activeProps={{
107 className: 'font-bold',
108 }}
109 >
110 Posts
111 </Link>
112 </div>
113 <hr />
114 <Outlet />
115 {/* Start rendering router matches */}
116 <TanStackRouterDevtools position="bottom-right" />
117 </>
118 )
120​
121const indexRoute = createRoute({
122 getParentRoute: () => rootRoute,
123 path: '/',
124}).update({
125 component: IndexComponent,
126})
127​
128function IndexComponent() {
129 return (
130 <div className="p-2">
131 <h3>Welcome Home!</h3>
132 </div>
133 )
135​
136const postsRoute = createRoute({
137 getParentRoute: () => rootRoute,
138 path: 'posts',
139 loader: fetchPosts,
140 component: PostsComponent,
141})
142​
143function PostsComponent() {
144 const posts = postsRoute.useLoaderData()
145​
146 return (
147 <div className="p-2 flex gap-2">
148 <ul className="list-disc pl-4">
149 {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map(
150 (post) => {
151 return (
152 <li key={post.id} className="whitespace-nowrap">
153 <Link
154 to={postRoute.to}
155 params={{
156 postId: post.id,
157 }}
158 className="flex py-1 text-blue-600 hover:opacity-75 gap-2 items-center"
159 activeProps={{ className: 'font-bold underline' }}
160 >
161 <div>{post.title.substring(0, 20)}</div>
162 <MatchRoute
163 to={postRoute.to}
164 params={{
165 postId: post.id,
166 }}
167 pending
168 >
169 {(match) => {
170 return <Spinner show={!!match} wait="delay-0" />
171 }}
172 </MatchRoute>
173 </Link>
174 </li>
175 )
176 },
177 )}
178 </ul>
179 <hr />
180 <Outlet />
181 </div>
182 )
184​
185class NotFoundError extends Error {}
186​
187const postRoute = createRoute({
188 getParentRoute: () => postsRoute,
189 path: '$postId',
190 loader: async ({ params: { postId } }) => fetchPost(postId),
191 errorComponent: PostErrorComponent,
192 component: PostComponent,
193})
194​
195function PostErrorComponent({ error }: ErrorComponentProps) {
196 if (error instanceof NotFoundError) {
197 return <div>{error.message}</div>
198 }
199​
200 return <ErrorComponent error={error} />
202​
203function PostComponent() {
204 const { post, commentsPromise } = postRoute.useLoaderData()
205​
206 return (
207 <div className="space-y-2">
208 <h4 className="text-xl font-bold underline">{post.title}</h4>
209 <div className="text-sm">{post.body}</div>
210 <React.Suspense
211 fallback={
212 <div className="flex items-center gap-2">
213 <Spinner />
214 Loading comments...
215 </div>
216 }
217 key={post.id}
218 >
219 <Await promise={commentsPromise}>
220 {(comments) => {
221 return (
222 <div className="space-y-2">
223 <h5 className="text-lg font-bold underline">Comments</h5>
224 {comments.map((comment) => {
225 return (
226 <div key={comment.id}>
227 <h6 className="text-md font-bold">{comment.name}</h6>
228 <div className="text-sm italic opacity-50">
229 {comment.email}
230 </div>
231 <div className="text-sm">{comment.body}</div>
232 </div>
233 )
234 })}
235 </div>
236 )
237 }}
238 </Await>
239 </React.Suspense>
240 </div>
241 )
243​
244const routeTree = rootRoute.addChildren([
245 postsRoute.addChildren([postRoute]),
246 indexRoute,
247])
248​
249// Set up a Router instance
250const router = createRouter({
251 routeTree,
252 defaultPreload: 'intent',
253 scrollRestoration: true,
254})
255​
256// Register things for typesafety
257declare module '@tanstack/react-router' {
258 interface Register {
259 router: typeof router
260 }
262​
263const rootElement = document.getElementById('app')!
264​
265if (!rootElement.innerHTML) {
266 const root = ReactDOM.createRoot(rootElement)
267​
268 root.render(<RouterProvider router={router} />)