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

devtools.tsx

95 lines2.4 KB

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