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

index.tsx

126 lines3.3 KB

1import React from 'react'
2import ReactDOM from 'react-dom/client'
3import {
4 QueryClient,
5 QueryClientProvider,
6 useQuery,
7 useQueryClient,
8} from '@tanstack/react-query'
9import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
10import { postsQueries } from './services/posts/queries'
11​
12const queryClient = new QueryClient()
13​
14function App() {
15 const [postId, setPostId] = React.useState<string | null>(null)
16​
17 return (
18 <QueryClientProvider client={queryClient}>
19 <p>
20 As you visit the posts below, you will notice them in a loading state
21 the first time you load them. However, after you return to this list and
22 click on any posts you have already visited again, you will see them
23 load instantly and background refresh right before your eyes!{' '}
24 <strong>
25 (You may need to throttle your network speed to simulate longer
26 loading sequences)
27 </strong>
28 </p>
29 {postId !== null ? (
30 <Post postId={postId} setPostId={setPostId} />
31 ) : (
32 <Posts setPostId={setPostId} />
33 )}
34 <ReactQueryDevtools initialIsOpen />
35 </QueryClientProvider>
36 )
38​
39function Posts({
40 setPostId,
41}: {
42 setPostId: React.Dispatch<React.SetStateAction<string | null>>
43}) {
44 const queryClient = useQueryClient()
45 const { status, data, error, isFetching } = useQuery(postsQueries.list())
46​
47 return (
48 <div>
49 <h1>Posts</h1>
50 <div>
51 {status === 'pending' ? (
52 'Loading...'
53 ) : status === 'error' ? (
54 <span>Error: {error.message}</span>
55 ) : (
56 <>
57 <div>
58 {data.map((post) => (
59 <p key={post.id}>
60 <a
61 onClick={() => setPostId(post.id)}
62 href="#"
63 style={
64 // We can find the existing query data here to show bold links for
65 // ones that are cached
66 queryClient.getQueryData(
67 postsQueries.detail(post.id).queryKey,
68 )
69 ? {
70 fontWeight: 'bold',
71 color: 'green',
72 }
73 : {}
74 }
75 >
76 {post.title}
77 </a>
78 </p>
79 ))}
80 </div>
81 <div>{isFetching ? 'Background Updating...' : ' '}</div>
82 </>
83 )}
84 </div>
85 </div>
86 )
88​
89function Post({
90 postId,
91 setPostId,
92}: {
93 postId: string
94 setPostId: React.Dispatch<React.SetStateAction<string | null>>
95}) {
96 const { status, data, error, isFetching } = useQuery(
97 postsQueries.detail(postId),
98 )
99​
100 return (
101 <div>
102 <div>
103 <a onClick={() => setPostId(null)} href="#">
104 Back
105 </a>
106 </div>
107 {status === 'pending' ? (
108 'Loading...'
109 ) : status === 'error' ? (
110 <span>Error: {error.message}</span>
111 ) : (
112 <>
113 <h1>{data.title}</h1>
114 <div>
115 <p>{data.body}</p>
116 </div>
117 <div>{isFetching ? 'Background Updating...' : ' '}</div>
118 </>
119 )}
120 </div>
121 )
123​
124const rootElement = document.getElementById('root')
125if (!rootElement) throw new Error('Missing #root element')
126ReactDOM.createRoot(rootElement).render(<App />)