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

devtools.tsx

100 lines2.6 KB

1'use client'
2import * as React from 'react'
3import { onlineManager, useQueryClient } from '@tanstack/react-query'
4import { TanstackQueryDevtools } from '@tanstack/query-devtools'
5import type {
6 DevToolsErrorType,
7 DevtoolsButtonPosition,
8 DevtoolsPosition,
9} from '@tanstack/query-devtools'
10import type { QueryClient } from '@tanstack/react-query'
11​
12export interface DevtoolsOptions {
13 /**
14 * Set this true if you want the dev tools to default to being open
15 */
16 initialIsOpen?: boolean
17 /**
18 * The position of the React Query logo to open and close the devtools panel.
19 * 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
20 * Defaults to 'bottom-right'.
21 */
22 buttonPosition?: DevtoolsButtonPosition
23 /**
24 * The position of the React Query devtools panel.
25 * 'top' | 'bottom' | 'left' | 'right'
26 * Defaults to 'bottom'.
27 */
28 position?: DevtoolsPosition
29 /**
30 * Custom instance of QueryClient
31 */
32 client?: QueryClient
33 /**
34 * Use this so you can define custom errors that can be shown in the devtools.
35 */
36 errorTypes?: Array<DevToolsErrorType>
37 /**
38 * Use this to pass a nonce to the style tag that is added to the document head. This is useful if you are using a Content Security Policy (CSP) nonce to allow inline styles.
39 */
40 styleNonce?: string
42​
43export function ReactQueryDevtools(
44 props: DevtoolsOptions,
45): React.ReactElement | null {
46 const queryClient = useQueryClient()
47 const client = props.client || queryClient
48 const ref = React.useRef<HTMLDivElement>(null)
49 const { buttonPosition, position, initialIsOpen, errorTypes, styleNonce } =
50 props
51 const [devtools] = React.useState(
52 new TanstackQueryDevtools({
53 client: client,
54 queryFlavor: 'React Query',
55 version: '5',
56 onlineManager,
57 buttonPosition,
58 position,
59 initialIsOpen,
60 errorTypes,
61 styleNonce,
62 }),
63 )
64​
65 React.useEffect(() => {
66 devtools.setClient(client)
67 }, [client, devtools])
68​
69 React.useEffect(() => {
70 if (buttonPosition) {
71 devtools.setButtonPosition(buttonPosition)
72 }
73 }, [buttonPosition, devtools])
74​
75 React.useEffect(() => {
76 if (position) {
77 devtools.setPosition(position)
78 }
79 }, [position, devtools])
80​
81 React.useEffect(() => {
82 devtools.setInitialIsOpen(initialIsOpen || false)
83 }, [initialIsOpen, devtools])
84​
85 React.useEffect(() => {
86 devtools.setErrorTypes(errorTypes || [])
87 }, [errorTypes, devtools])
88​
89 React.useEffect(() => {
90 if (ref.current) {
91 devtools.mount(ref.current)
92 }
93​
94 return () => {
95 devtools.unmount()
96 }
97 }, [devtools])
98​
99 return <div className="tsqd-parent-container" ref={ref}></div>