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

main.tsx

222 lines5.2 KB

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