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

route.tsx

62 lines1.7 KB

1import * as React from 'react'
2import { Link, Outlet, createFileRoute } from '@tanstack/react-router'
3​
4export type PostType = {
5 id: string
6 title: string
7 body: string
8}
9​
10export const Route = createFileRoute('/posts')({
11 loader: async () => {
12 console.info('Fetching posts...')
13 await new Promise((r) =>
14 setTimeout(r, 300 + Math.round(Math.random() * 300)),
15 )
16 return fetch('https://jsonplaceholder.typicode.com/posts')
17 .then((d) => d.json() as Promise<Array<PostType>>)
18 .then((d) => d.slice(0, 10))
19 },
20 component: PostsComponent,
21})
22​
23function PostsComponent() {
24 const posts = Route.useLoaderData()
25​
26 return (
27 <div className="p-2 flex gap-2">
28 <ul className="list-disc pl-4">
29 {posts.map((post) => {
30 return (
31 <li key={post.id} className="whitespace-nowrap">
32 <Link
33 to="/posts/$postId"
34 params={{
35 postId: post.id,
36 }}
37 className="block py-1 text-blue-800 hover:text-blue-600"
38 activeProps={{ className: 'text-black font-bold' }}
39 >
40 <div>{post.title.substring(0, 20)}</div>
41 </Link>
42 </li>
43 )
44 })}
45 <li className="whitespace-nowrap">
46 <Link
47 to="/posts/$postId"
48 params={{
49 postId: 'does-not-exist',
50 }}
51 className="block py-1 text-blue-800 hover:text-blue-600"
52 activeProps={{ className: 'text-black font-bold' }}
53 >
54 <div>This post does not exist</div>
55 </Link>
56 </li>
57 </ul>
58 <hr />
59 <Outlet />
60 </div>
61 )