Open History to see the last commit
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 )
37}
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 )
87}
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 )
122}
123β
124const rootElement = document.getElementById('root')
125if (!rootElement) throw new Error('Missing #root element')
126ReactDOM.createRoot(rootElement).render(<App />)