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

$postId.tsx

37 lines894 Bytes

1import * as React from 'react'
2import { useLoaderData, useMatch } from '@tanstack/react-router'
3import { routeConfig } from '../../routes.generated/posts/$postId'
4​
5export type PostType = {
6 id: string
7 title: string
8 body: string
9}
10​
11routeConfig.generate({
12 component: Post,
13 loader: async ({ params: { postId } }) => {
14 console.log(`Fetching post with id ${postId}...`)
15​
16 await new Promise((r) => setTimeout(r, Math.round(Math.random() * 300)))
17​
18 const post = await fetch(
19 `https://jsonplaceholder.typicode.com/posts/${postId}`,
20 ).then((r) => r.json() as Promise<PostType>)
21​
22 return {
23 post,
24 }
25 },
26})
27​
28function Post() {
29 const { post } = useLoaderData({ from: routeConfig.id })
30​
31 return (
32 <div className="space-y-2">
33 <h4 className="text-xl font-bold underline">{post.title}</h4>
34 <div className="text-sm">{post.body}</div>
35 </div>
36 )