Open History to see the last commit
1import React, { StrictMode } from 'react'
2import ReactDOM from 'react-dom/client'
3import {
4 Outlet,
5 RouterProvider,
6 createReactRouter,
7 createRouteConfig,
8 Link,
9 useMatch,
10 useParams,
11} from '@tanstack/react-router'
12import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
13import {
14 useQuery,
15 useQueryClient,
16 QueryClient,
17 QueryClientProvider,
18} from '@tanstack/react-query'
19import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
20β
21import axios from 'axios'
22β
23type PostType = {
24 id: string
25 title: string
26 body: string
27}
28β
29const rootRoute = createRouteConfig({
30 component: () => {
31 return (
32 <>
33 <div className="p-2 flex gap-2 text-lg">
34 <Link
35 to="/"
36 activeProps={{
37 className: 'font-bold',
38 }}
39 activeOptions={{ exact: true }}
40 >
41 Home
42 </Link>{' '}
43 <Link
44 to="/posts"
45 activeProps={{
46 className: 'font-bold',
47 }}
48 >
49 Posts
50 </Link>
51 </div>
52 <hr />
53 <Outlet /> {/* Start rendering router matches */}
54 <TanStackRouterDevtools position="bottom-left" />
55 </>
56 )
57 },
58})
59β
60const indexRoute = rootRoute.createRoute({
61 path: '/',
62 component: () => {
63 return (
64 <div className="p-2">
65 <h3>Welcome Home!</h3>
66 </div>
67 )
68 },
69})
70β
71const postsRoute = rootRoute.createRoute({
72 path: 'posts',
73 loader: async () => {
74 queryClient.getQueryData(['posts']) ??
75 (await queryClient.prefetchQuery(['posts'], fetchPosts))
76 return {}
77 },
78 component: () => {
79 const postsQuery = usePosts()
80β
81 return (
82 <div className="p-2 flex gap-2">
83 <ul className="list-disc pl-4">
84 {postsQuery.data?.map((post) => {
85 return (
86 <li key={post.id} className="whitespace-nowrap">
87 <Link
88 to={postRoute.id}
89 params={{
90 postId: post.id,
91 }}
92 className="block py-1 text-blue-800 hover:text-blue-600"
93 activeProps={{ className: 'text-black font-bold' }}
94 >
95 <div>{post.title.substring(0, 20)}</div>
96 </Link>
97 </li>
98 )
99 })}
100 </ul>
101 <hr />
102 <Outlet />
103 </div>
104 )
105 },
106 errorComponent: () => 'Oh crap!',
107})
108β
109const postsIndexRoute = postsRoute.createRoute({
110 path: '/',
111 component: () => {
112 return (
113 <>
114 <div>Select a post.</div>
115 </>
116 )
117 },
118})
119β
120const postRoute = postsRoute.createRoute({
121 path: '$postId',
122 loader: async ({ params: { postId } }) => {
123 queryClient.getQueryData(['posts', postId]) ??
124 (await queryClient.prefetchQuery(['posts', postId], () =>
125 fetchPostById(postId),
126 ))
127 return {}
128 },
129 component: () => {
130 const { postId } = useParams({ from: postRoute.id })
131 const postQuery = usePost(postId)
132β
133 return (
134 <div className="space-y-2">
135 <h4 className="text-xl font-bold underline">{postQuery.data?.title}</h4>
136 <div className="text-sm">{postQuery.data?.body}</div>
137 </div>
138 )
139 },
140})
141β
142const routeConfig = rootRoute.addChildren([
143 indexRoute,
144 postsRoute.addChildren([postsIndexRoute, postRoute]),
145])
146β
147// Set up a ReactRouter instance
148const router = createReactRouter({
149 routeConfig,
150 defaultPreload: 'intent',
151})
152β
153declare module '@tanstack/react-router' {
154 interface RegisterRouter {
155 router: typeof router
156 }
157}
158β
159const queryClient = new QueryClient()
160β
161function App() {
162 return (
163 // Build our routes and render our router
164 <>
165 <QueryClientProvider client={queryClient}>
166 <RouterProvider router={router} />
167 <ReactQueryDevtools
168 initialIsOpen
169 position="bottom-left"
170 toggleButtonProps={{
171 style: {
172 marginLeft: '5.5rem',
173 transform: `scale(.7)`,
174 transformOrigin: 'bottom left',
175 },
176 }}
177 />
178 </QueryClientProvider>
179 </>
180 )
181}
182β
183async function fetchPosts() {
184 console.log('Fetching posts...')
185 await new Promise((r) => setTimeout(r, 500))
186 return axios
187 .get<PostType[]>('https://jsonplaceholder.typicode.com/posts')
188 .then((r) => r.data.slice(0, 10))
189}
190β
191async function fetchPostById(postId: string) {
192 console.log(`Fetching post with id ${postId}...`)
193 await new Promise((r) => setTimeout(r, 500))
194β
195 return await axios
196 .get<PostType>(`https://jsonplaceholder.typicode.com/posts/${postId}`)
197 .then((r) => r.data)
198}
199β
200function usePosts() {
201 return useQuery(['posts'], fetchPosts)
202}
203β
204function usePost(postId: string) {
205 return useQuery(['posts', postId], () => fetchPostById(postId), {
206 enabled: !!postId,
207 })
208}
209β
210const rootElement = document.getElementById('app')!
211if (!rootElement.innerHTML) {
212 const root = ReactDOM.createRoot(rootElement)
213 root.render(
214 <StrictMode>
215 <App />
216 </StrictMode>,
217 )
218}