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

index.tsx

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