Open History to see the last commit
1import { AST_NODE_TYPES, ESLintUtils } from '@typescript-eslint/utils'
2import { ASTUtils } from '../../utils/ast-utils'
3import { getDocsUrl } from '../../utils/get-docs-url'
4import { detectTanstackQueryImports } from '../../utils/detect-react-query-imports'
5import type { TSESLint } from '@typescript-eslint/utils'
6import type { ExtraRuleDocs } from '../../types'
7β
8export const name = 'stable-query-client'
9β
10const createRule = ESLintUtils.RuleCreator<ExtraRuleDocs>(getDocsUrl)
11β
12export const rule = createRule({
13 name,
14 meta: {
15 type: 'problem',
16 docs: {
17 description: 'Makes sure that QueryClient is stable',
18 recommended: 'error',
19 },
20 messages: {
21 unstable: [
22 'QueryClient is not stable. It should be either extracted from the component or wrapped in React.useState.',
23 'See https://tkdodo.eu/blog/react-query-fa-qs#2-the-queryclient-is-not-stable',
24 ].join('\n'),
25 fixTo: 'Fix to {{result}}',
26 },
27 hasSuggestions: true,
28 fixable: 'code',
29 schema: [],
30 },
31 defaultOptions: [],
32β
33 create: detectTanstackQueryImports((context, _, helpers) => {
34 return {
35 NewExpression: (node) => {
36 if (
37 node.callee.type !== AST_NODE_TYPES.Identifier ||
38 node.callee.name !== 'QueryClient' ||
39 node.parent.type !== AST_NODE_TYPES.VariableDeclarator ||
40 !helpers.isSpecificTanstackQueryImport(
41 node.callee,
42 '@tanstack/react-query',
43 )
44 ) {
45 return
46 }
47β
48 const fnAncestor = ASTUtils.getFunctionAncestor(
49 context.sourceCode,
50 node,
51 )
52 const isReactServerComponent = fnAncestor?.async === true
53β
54 if (
55 !ASTUtils.isValidReactComponentOrHookName(fnAncestor?.id) ||
56 isReactServerComponent
57 ) {
58 return
59 }
60β
61 context.report({
62 node: node.parent,
63 messageId: 'unstable',
64 fix: (() => {
65 const { parent } = node
66β
67 if (parent.id.type !== AST_NODE_TYPES.Identifier) {
68 return
69 }
70β
71 // we need the fallbacks for backwards compat with eslint < 8.37.0
72 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
73 const sourceCode = context.sourceCode ?? context.getSourceCode()
74 const nodeText = sourceCode.getText(node)
75 const variableName = parent.id.name
76β
77 return (fixer: TSESLint.RuleFixer) => {
78 return fixer.replaceTextRange(
79 [parent.range[0], parent.range[1]],
80 `[${variableName}] = React.useState(() => ${nodeText})`,
81 )
82 }
83 })(),
84 })
85 },
86 }
87 }),
88})