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

index.tsx

177 lines4.1 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 { gql, request } from 'graphql-request'
11​
12const endpoint = 'https://graphqlzero.almansi.me/api'
13​
14const queryClient = new QueryClient()
15​
16type Post = {
17 id: number
18 title: string
19 body: string
21​
22function App() {
23 const [postId, setPostId] = React.useState(-1)
24​
25 return (
26 <QueryClientProvider client={queryClient}>
27 <p>
28 As you visit the posts below, you will notice them in a loading state
29 the first time you load them. However, after you return to this list and
30 click on any posts you have already visited again, you will see them
31 load instantly and background refresh right before your eyes!{' '}
32 <strong>
33 (You may need to throttle your network speed to simulate longer
34 loading sequences)
35 </strong>
36 </p>
37 {postId > -1 ? (
38 <Post postId={postId} setPostId={setPostId} />
39 ) : (
40 <Posts setPostId={setPostId} />
41 )}
42 <ReactQueryDevtools initialIsOpen />
43 </QueryClientProvider>
44 )
46​
47function usePosts() {
48 return useQuery({
49 queryKey: ['posts'],
50 queryFn: async () => {
51 const {
52 posts: { data },
53 } = await request<{ posts: { data: Array<Post> } }>(
54 endpoint,
55 gql`
56 query {
57 posts {
58 data {
59 id
60 title
61 }
62 }
63 }
64 `,
65 )
66 return data
67 },
68 })
70​
71function Posts({
72 setPostId,
73}: {
74 setPostId: React.Dispatch<React.SetStateAction<number>>
75}) {
76 const queryClient = useQueryClient()
77 const { status, data, error, isFetching } = usePosts()
78​
79 return (
80 <div>
81 <h1>Posts</h1>
82 <div>
83 {status === 'pending' ? (
84 'Loading...'
85 ) : status === 'error' ? (
86 <span>Error: {error.message}</span>
87 ) : (
88 <>
89 <div>
90 {data.map((post) => (
91 <p key={post.id}>
92 <a
93 onClick={() => setPostId(post.id)}
94 href="#"
95 style={
96 // We can find the existing query data here to show bold links for
97 // ones that are cached
98 queryClient.getQueryData(['post', post.id])
99 ? {
100 fontWeight: 'bold',
101 color: 'green',
102 }
103 : {}
104 }
105 >
106 {post.title}
107 </a>
108 </p>
109 ))}
110 </div>
111 <div>{isFetching ? 'Background Updating...' : ' '}</div>
112 </>
113 )}
114 </div>
115 </div>
116 )
118​
119function usePost(postId: number) {
120 return useQuery({
121 queryKey: ['post', postId],
122 queryFn: async () => {
123 const { post } = await request<{ post: Post }>(
124 endpoint,
125 gql`
126 query {
127 post(id: ${postId}) {
128 id
129 title
130 body
131 }
132 }
133 `,
134 )
135​
136 return post
137 },
138 enabled: !!postId,
139 })
141​
142function Post({
143 postId,
144 setPostId,
145}: {
146 postId: number
147 setPostId: React.Dispatch<React.SetStateAction<number>>
148}) {
149 const { status, data, error, isFetching } = usePost(postId)
150​
151 return (
152 <div>
153 <div>
154 <a onClick={() => setPostId(-1)} href="#">
155 Back
156 </a>
157 </div>
158 {!postId || status === 'pending' ? (
159 'Loading...'
160 ) : status === 'error' ? (
161 <span>Error: {error.message}</span>
162 ) : (
163 <>
164 <h1>{data.title}</h1>
165 <div>
166 <p>{data.body}</p>
167 </div>
168 <div>{isFetching ? 'Background Updating...' : ' '}</div>
169 </>
170 )}
171 </div>
172 )
174​
175const rootElement = document.getElementById('root')
176if (!rootElement) throw new Error('Missing #root element')
177ReactDOM.createRoot(rootElement).render(<App />)