-
-
Notifications
You must be signed in to change notification settings - Fork 698
/
main.tsx
223 lines (200 loc) · 5.19 KB
/
main.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import React from 'react'
import ReactDOM from 'react-dom/client'
import {
ErrorComponent,
Link,
Outlet,
RouterProvider,
createRootRoute,
createRoute,
createRouter,
} from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/router-devtools'
import axios from 'redaxios'
import { z } from 'zod'
import type {
ErrorComponentProps,
SearchSchemaInput,
} from '@tanstack/react-router'
type PostType = {
id: number
title: string
body: string
}
const fetchPosts = async () => {
console.info('Fetching posts...')
await new Promise((r) => setTimeout(r, 300))
return axios
.get<Array<PostType>>('https://jsonplaceholder.typicode.com/posts')
.then((r) => r.data.slice(0, 10))
}
const fetchPost = async (postId: number) => {
console.info(`Fetching post with id ${postId}...`)
await new Promise((r) => setTimeout(r, 300))
const post = await axios
.get<PostType>(`https://jsonplaceholder.typicode.com/posts/${postId}`)
.catch((err) => {
if (err.status === 404) {
throw new NotFoundError(`Post with id "${postId}" not found!`)
}
throw err
})
.then((r) => r.data)
return post
}
const rootRoute = createRootRoute({
component: RootComponent,
notFoundComponent: () => {
return <p>This is the notFoundComponent configured on root route</p>
},
})
function RootComponent() {
return (
<div className="bg-gradient-to-r from-green-700 to-lime-600 text-white">
<div className="p-2 flex gap-2 text-lg bg-black/40 shadow-xl">
<Link
to="/"
activeProps={{
className: 'font-bold',
}}
activeOptions={{ exact: true }}
>
Home
</Link>{' '}
<Link
to="/posts"
activeProps={{
className: 'font-bold',
}}
>
Posts
</Link>{' '}
<Link
// @ts-expect-error
to="/this-route-does-not-exist"
activeProps={{
className: 'font-bold',
}}
>
This Route Does Not Exist
</Link>
</div>
<Outlet />
<TanStackRouterDevtools position="bottom-right" />
</div>
)
}
const indexRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/',
component: IndexComponent,
})
function IndexComponent() {
return (
<div className="p-2">
<h3>Welcome Home!</h3>
</div>
)
}
const postsRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'posts',
loader: () => fetchPosts(),
component: PostsComponent,
})
function PostsComponent() {
const posts = postsRoute.useLoaderData()
return (
<div className="p-2 flex gap-2">
<div className="list-disc bg-gray-800/70 rounded-lg divide-y divide-green-500/30">
{posts.map((post, index) => {
return (
<div key={post.id} className="whitespace-nowrap">
<Link
to={postRoute.to}
search={{
postId: post.id,
color: index % 2 ? 'red' : undefined,
}}
className="block py-1 px-2 text-green-300 hover:text-green-200"
activeProps={{ className: '!text-white font-bold' }}
>
<div>{post.title.substring(0, 20)}</div>
</Link>
</div>
)
})}
</div>
<Outlet />
</div>
)
}
const postsIndexRoute = createRoute({
getParentRoute: () => postsRoute,
path: '/',
component: PostsIndexComponent,
})
function PostsIndexComponent() {
return <div>Select a post.</div>
}
class NotFoundError extends Error {}
const postRoute = createRoute({
getParentRoute: () => postsRoute,
path: 'post',
validateSearch: (
input: {
postId: number
color?: 'white' | 'red' | 'green'
} & SearchSchemaInput,
) =>
z
.object({
postId: z.number().catch(1),
color: z.enum(['white', 'red', 'green']).catch('white'),
})
.parse(input),
loaderDeps: ({ search: { postId } }) => ({
postId,
}),
errorComponent: PostErrorComponent,
loader: ({ deps: { postId } }) => fetchPost(postId),
component: PostComponent,
})
function PostErrorComponent({ error }: ErrorComponentProps) {
if (error instanceof NotFoundError) {
return <div>{error.message}</div>
}
return <ErrorComponent error={error} />
}
function PostComponent() {
const post = postRoute.useLoaderData()
const { color } = postRoute.useSearch()
return (
<div className="space-y-2">
<h4 className="text-xl font-bold">{post.title}</h4>
<hr className="opacity-20" />
<div className={`text-sm text-${color}-300`}>{post.body}</div>
</div>
)
}
const routeTree = rootRoute.addChildren([
postsRoute.addChildren([postRoute, postsIndexRoute]),
indexRoute,
])
// Set up a Router instance
const router = createRouter({
routeTree,
defaultPreload: 'intent',
defaultStaleTime: 5000,
})
// Register things for typesafety
declare module '@tanstack/react-router' {
interface Register {
router: typeof router
}
}
const rootElement = document.getElementById('app')!
if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement)
root.render(<RouterProvider router={router} />)
}