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

App.tsx

53 lines1.7 KB

1import { useQuery } from '@tanstack/preact-query'
2import { commentsQueries } from './services/comments/queries'
3import { postsQueries } from './services/posts/queries'
4import { usersQueries } from './services/users/queries'
5​
6export default function App() {
7 // This query was prefetched on the server, so its data is already in the
8 // server-rendered markup and is available immediately on the client
9 const postsQuery = useQuery(postsQueries.list())
10​
11 // This query depends on the posts, and was prefetched on the server as well
12 const authorQuery = useQuery(
13 usersQueries.detail(postsQuery.data?.[0]?.userId),
14 )
15​
16 // This query was not prefetched on the server and will not start
17 // fetching until on the client, both patterns are fine to mix
18 const commentsQuery = useQuery(commentsQueries.list())
19​
20 return (
21 <div>
22 <h1>Server Rendering with Preact Query</h1>
23 <h2>Comments</h2>
24 <p>
25 {commentsQuery.isPending
26 ? 'Loading comments on the client...'
27 : commentsQuery.isError
28 ? `Error: ${commentsQuery.error.message}`
29 : `${commentsQuery.data.length} comments`}
30 </p>
31 <h2>Author of the first post</h2>
32 <p>
33 {authorQuery.isPending
34 ? 'Loading author...'
35 : authorQuery.isError
36 ? `Error: ${authorQuery.error.message}`
37 : authorQuery.data.name}
38 </p>
39 <h2>Posts</h2>
40 {postsQuery.isPending ? (
41 'Loading posts...'
42 ) : postsQuery.isError ? (
43 <span>Error: {postsQuery.error.message}</span>
44 ) : (
45 <ul>
46 {postsQuery.data.map((post) => (
47 <li key={post.id}>{post.title}</li>
48 ))}
49 </ul>
50 )}
51 </div>
52 )