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 type { QueryKey } from '@tanstack/react-query'
11β
12type Post = {
13 id: number
14 title: string
15 body: string
16}
17β
18// Define a default query function that will receive the query key
19const defaultQueryFn = async ({ queryKey }: { queryKey: QueryKey }) => {
20 const response = await fetch(
21 `https://jsonplaceholder.typicode.com${queryKey[0]}`,
22 )
23 return await response.json()
24}
25β
26// provide the default query function to your app via the query client
27const queryClient = new QueryClient({
28 defaultOptions: {
29 queries: {
30 queryFn: defaultQueryFn,
31 },
32 },
33})
34β
35function App() {
36 const [postId, setPostId] = React.useState(-1)
37β
38 return (
39 <QueryClientProvider client={queryClient}>
40 <p>
41 As you visit the posts below, you will notice them in a loading state
42 the first time you load them. However, after you return to this list and
43 click on any posts you have already visited again, you will see them
44 load instantly and background refresh right before your eyes!{' '}
45 <strong>
46 (You may need to throttle your network speed to simulate longer
47 loading sequences)
48 </strong>
49 </p>
50 {postId > -1 ? (
51 <Post postId={postId} setPostId={setPostId} />
52 ) : (
53 <Posts setPostId={setPostId} />
54 )}
55 <ReactQueryDevtools initialIsOpen />
56 </QueryClientProvider>
57 )
58}
59β
60function Posts({
61 setPostId,
62}: {
63 setPostId: React.Dispatch<React.SetStateAction<number>>
64}) {
65 const queryClient = useQueryClient()
66β
67 // All you have to do now is pass a key!
68 const { status, data, error, isFetching } = useQuery<Array<Post>>({
69 queryKey: ['/posts'],
70 })
71β
72 return (
73 <div>
74 <h1>Posts</h1>
75 <div>
76 {status === 'pending' ? (
77 'Loading...'
78 ) : status === 'error' ? (
79 <span>Error: {error.message}</span>
80 ) : (
81 <>
82 <div>
83 {data.map((post) => (
84 <p key={post.id}>
85 <a
86 onClick={() => setPostId(post.id)}
87 href="#"
88 style={
89 // We can use the queryCache here to show bold links for
90 // ones that are cached
91 queryClient.getQueryData([`/posts/${post.id}`])
92 ? {
93 fontWeight: 'bold',
94 color: 'green',
95 }
96 : {}
97 }
98 >
99 {post.title}
100 </a>
101 </p>
102 ))}
103 </div>
104 <div>{isFetching ? 'Background Updating...' : ' '}</div>
105 </>
106 )}
107 </div>
108 </div>
109 )
110}
111β
112function Post({
113 postId,
114 setPostId,
115}: {
116 postId: number
117 setPostId: React.Dispatch<React.SetStateAction<number>>
118}) {
119 // You can even leave out the queryFn and just go straight into options
120 const { status, data, error, isFetching } = useQuery<Post>({
121 queryKey: [`/posts/${postId}`],
122 enabled: !!postId,
123 })
124β
125 return (
126 <div>
127 <div>
128 <a onClick={() => setPostId(-1)} href="#">
129 Back
130 </a>
131 </div>
132 {!postId || status === 'pending' ? (
133 'Loading...'
134 ) : status === 'error' ? (
135 <span>Error: {error.message}</span>
136 ) : (
137 <>
138 <h1>{data.title}</h1>
139 <div>
140 <p>{data.body}</p>
141 </div>
142 <div>{isFetching ? 'Background Updating...' : ' '}</div>
143 </>
144 )}
145 </div>
146 )
147}
148β
149const rootElement = document.getElementById('root')
150if (!rootElement) throw new Error('Missing #root element')
151ReactDOM.createRoot(rootElement).render(<App />)