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

ActiveQuery.tsx

388 lines9.9 KB

1import React from 'react'
2import type { QueryCache, QueryClient } from '@tanstack/react-query'
3​
4import useSubscribeToQueryCache from '../useSubscribeToQueryCache'
5import { Button, Code, Select, ActiveQueryPanel } from '../styledComponents'
6​
7import {
8 getQueryStatusLabel,
9 getQueryStatusColor,
10 displayValue,
11} from '../utils'
12import Explorer from '../Explorer'
13import type { DevToolsErrorType } from '../types'
14import { defaultTheme as theme } from '../theme'
15​
16// eslint-disable-next-line @typescript-eslint/no-empty-function
17function noop() {}
18​
19/**
20 * Panel for the query currently being inspected
21 *
22 * It displays query details (key, observers...), query actions,
23 * the data explorer and the query explorer
24 */
25const ActiveQuery = ({
26 queryCache,
27 activeQueryHash,
28 queryClient,
29 errorTypes,
30}: {
31 queryCache: QueryCache
32 activeQueryHash: string
33 queryClient: QueryClient
34 errorTypes: DevToolsErrorType[]
35}) => {
36 const activeQuery = useSubscribeToQueryCache(queryCache, () =>
37 queryCache.getAll().find((query) => query.queryHash === activeQueryHash),
38 )
39​
40 const activeQueryState = useSubscribeToQueryCache(
41 queryCache,
42 () =>
43 queryCache.getAll().find((query) => query.queryHash === activeQueryHash)
44 ?.state,
45 )
46​
47 const isStale =
48 useSubscribeToQueryCache(queryCache, () =>
49 queryCache
50 .getAll()
51 .find((query) => query.queryHash === activeQueryHash)
52 ?.isStale(),
53 ) ?? false
54​
55 const observerCount =
56 useSubscribeToQueryCache(queryCache, () =>
57 queryCache
58 .getAll()
59 .find((query) => query.queryHash === activeQueryHash)
60 ?.getObserversCount(),
61 ) ?? 0
62​
63 const handleRefetch = () => {
64 const promise = activeQuery?.fetch()
65 promise?.catch(noop)
66 }
67​
68 const currentErrorTypeName = React.useMemo(() => {
69 if (activeQuery && activeQueryState?.error) {
70 const errorType = errorTypes.find(
71 (type) =>
72 type.initializer(activeQuery).toString() ===
73 activeQueryState.error?.toString(),
74 )
75 return errorType?.name
76 }
77 return undefined
78 }, [activeQuery, activeQueryState?.error, errorTypes])
79​
80 if (!activeQuery || !activeQueryState) {
81 return null
82 }
83​
84 const triggerError = (errorType?: DevToolsErrorType) => {
85 const error =
86 errorType?.initializer(activeQuery) ??
87 new Error('Unknown error from devtools')
88​
89 const __previousQueryOptions = activeQuery.options
90​
91 activeQuery.setState({
92 status: 'error',
93 error,
94 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
95 fetchMeta: {
96 ...activeQuery.state.fetchMeta,
97 __previousQueryOptions,
98 } as any,
99 })
100 }
101​
102 const restoreQueryAfterLoadingOrError = () => {
103 activeQuery.fetch(
104 (activeQuery.state.fetchMeta as any)?.__previousQueryOptions,
105 {
106 // Make sure this fetch will cancel the previous one
107 cancelRefetch: true,
108 },
109 )
110 }
111​
112 return (
113 <ActiveQueryPanel>
114 <div
115 style={{
116 padding: '.5em',
117 background: theme.backgroundAlt,
118 position: 'sticky',
119 top: 0,
120 zIndex: 1,
121 }}
122 >
123 Query Details
124 </div>
125 <div
126 style={{
127 padding: '.5em',
128 }}
129 >
130 <div
131 style={{
132 marginBottom: '.5em',
133 display: 'flex',
134 alignItems: 'flex-start',
135 justifyContent: 'space-between',
136 }}
137 >
138 <Code
139 style={{
140 lineHeight: '1.8em',
141 }}
142 >
143 <pre
144 style={{
145 margin: 0,
146 padding: 0,
147 overflow: 'auto',
148 }}
149 >
150 {displayValue(activeQuery.queryKey, true)}
151 </pre>
152 </Code>
153 <span
154 style={{
155 padding: '0.3em .6em',
156 borderRadius: '0.4em',
157 fontWeight: 'bold',
158 textShadow: '0 2px 10px black',
159 background: getQueryStatusColor({
160 queryState: activeQueryState,
161 isStale: isStale,
162 observerCount: observerCount,
163 theme,
164 }),
165 flexShrink: 0,
166 }}
167 >
168 {getQueryStatusLabel(activeQuery)}
169 </span>
170 </div>
171 <div
172 style={{
173 marginBottom: '.5em',
174 display: 'flex',
175 alignItems: 'center',
176 justifyContent: 'space-between',
177 }}
178 >
179 Observers: <Code>{observerCount}</Code>
180 </div>
181 <div
182 style={{
183 display: 'flex',
184 alignItems: 'center',
185 justifyContent: 'space-between',
186 }}
187 >
188 Last Updated:{' '}
189 <Code>
190 {new Date(activeQueryState.dataUpdatedAt).toLocaleTimeString()}
191 </Code>
192 </div>
193 </div>
194 <div
195 style={{
196 background: theme.backgroundAlt,
197 padding: '.5em',
198 position: 'sticky',
199 top: 0,
200 zIndex: 1,
201 }}
202 >
203 Actions
204 </div>
205 <div
206 style={{
207 padding: '0.5em',
208 display: 'flex',
209 flexWrap: 'wrap',
210 gap: '0.5em',
211 alignItems: 'flex-end',
212 }}
213 >
214 <Button
215 type="button"
216 onClick={handleRefetch}
217 disabled={activeQueryState.fetchStatus === 'fetching'}
218 style={{
219 background: theme.active,
220 }}
221 >
222 Refetch
223 </Button>{' '}
224 <Button
225 type="button"
226 onClick={() => queryClient.invalidateQueries(activeQuery)}
227 style={{
228 background: theme.warning,
229 color: theme.inputTextColor,
230 }}
231 >
232 Invalidate
233 </Button>{' '}
234 <Button
235 type="button"
236 onClick={() => queryClient.resetQueries(activeQuery)}
237 style={{
238 background: theme.gray,
239 }}
240 >
241 Reset
242 </Button>{' '}
243 <Button
244 type="button"
245 onClick={() => queryClient.removeQueries(activeQuery)}
246 style={{
247 background: theme.danger,
248 }}
249 >
250 Remove
251 </Button>{' '}
252 <Button
253 type="button"
254 onClick={() => {
255 // Return early if the query is already restoring
256 if (
257 activeQuery.state.fetchStatus === 'fetching' &&
258 typeof (activeQuery.state.fetchMeta as any)
259 ?.__previousQueryOptions === 'undefined'
260 ) {
261 return
262 }
263 if (activeQuery.state.data === undefined) {
264 restoreQueryAfterLoadingOrError()
265 } else {
266 const __previousQueryOptions = activeQuery.options
267 // Trigger a fetch in order to trigger suspense as well.
268 activeQuery.fetch({
269 ...__previousQueryOptions,
270 queryFn: () => {
271 return new Promise(() => {
272 // Never resolve
273 })
274 },
275 gcTime: -1,
276 })
277 activeQuery.setState({
278 data: undefined,
279 status: 'pending',
280 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
281 fetchMeta: {
282 ...activeQuery.state.fetchMeta,
283 __previousQueryOptions,
284 } as any,
285 })
286 }
287 }}
288 style={{
289 background: theme.paused,
290 }}
291 >
292 {activeQuery.state.status === 'pending' ? 'Restore' : 'Trigger'}{' '}
293 loading
294 </Button>{' '}
295 {errorTypes.length === 0 || activeQuery.state.status === 'error' ? (
296 <Button
297 type="button"
298 onClick={() => {
299 if (!activeQuery.state.error) {
300 triggerError()
301 } else {
302 queryClient.resetQueries(activeQuery)
303 }
304 }}
305 style={{
306 background: theme.danger,
307 }}
308 >
309 {activeQuery.state.status === 'error' ? 'Restore' : 'Trigger'} error
310 </Button>
311 ) : (
312 <label>
313 Trigger error:
314 <Select
315 value={currentErrorTypeName ?? ''}
316 style={{ marginInlineStart: '.5em' }}
317 onChange={(e) => {
318 const errorType = errorTypes.find(
319 (t) => t.name === e.target.value,
320 )
321​
322 triggerError(errorType)
323 }}
324 >
325 <option key="" value="" />
326 {errorTypes.map((errorType) => (
327 <option key={errorType.name} value={errorType.name}>
328 {errorType.name}
329 </option>
330 ))}
331 </Select>
332 </label>
333 )}
334 </div>
335 <div
336 style={{
337 background: theme.backgroundAlt,
338 padding: '.5em',
339 position: 'sticky',
340 top: 0,
341 zIndex: 1,
342 }}
343 >
344 Data Explorer
345 </div>
346 <div
347 style={{
348 padding: '.5em',
349 }}
350 >
351 <Explorer
352 label="Data"
353 value={activeQueryState.data}
354 defaultExpanded={{}}
355 copyable
356 />
357 </div>
358 <div
359 style={{
360 background: theme.backgroundAlt,
361 padding: '.5em',
362 position: 'sticky',
363 top: 0,
364 zIndex: 1,
365 }}
366 >
367 Query Explorer
368 </div>
369 <div
370 style={{
371 padding: '.5em',
372 }}
373 >
374 <Explorer
375 label="Query"
376 value={activeQuery}
377 defaultExpanded={{
378 queryKey: true,
379 }}
380 />
381 </div>
382 </ActiveQueryPanel>
383 )
385​
386ActiveQuery.displayName = 'ActiveQuery'
387​
388export default ActiveQuery