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 !helpers.isSpecificTanstackQueryImport(
40 node.callee,
41 '@tanstack/react-query',
42 )
43 ) {
44 return
45 }
46β
47 const fnAncestor = context.sourceCode
48 .getAncestors(node)
49 .reverse()
50 .find((ancestor) =>
51 ASTUtils.isNodeOfOneOf(ancestor, [
52 AST_NODE_TYPES.FunctionDeclaration,
53 AST_NODE_TYPES.FunctionExpression,
54 AST_NODE_TYPES.ArrowFunctionExpression,
55 ]),
56 )
57 const fnName =
58 fnAncestor?.parent.type === AST_NODE_TYPES.VariableDeclarator &&
59 fnAncestor.parent.id.type === AST_NODE_TYPES.Identifier
60 ? fnAncestor.parent.id
61 : fnAncestor?.id
62 const isReactServerComponent = fnAncestor?.async === true
63β
64 if (
65 !ASTUtils.isValidReactComponentOrHookName(fnName) ||
66 isReactServerComponent
67 ) {
68 return
69 }
70β
71 context.report({
72 node:
73 node.parent.type === AST_NODE_TYPES.VariableDeclarator
74 ? node.parent
75 : node,
76 messageId: 'unstable',
77 fix: (() => {
78 const { parent } = node
79β
80 if (
81 parent.type !== AST_NODE_TYPES.VariableDeclarator ||
82 parent.id.type !== AST_NODE_TYPES.Identifier
83 ) {
84 return
85 }
86β
87 // we need the fallbacks for backwards compat with eslint < 8.37.0
88 // oxlint-disable-next-line typescript/no-unnecessary-condition
89 const sourceCode = context.sourceCode ?? context.getSourceCode()
90 const nodeText = sourceCode.getText(node)
91 const variableName = parent.id.name
92β
93 return (fixer: TSESLint.RuleFixer) => {
94 return fixer.replaceTextRange(
95 [parent.range[0], parent.range[1]],
96 `[${variableName}] = React.useState(() => ${nodeText})`,
97 )
98 }
99 })(),
100 })
101 },
102 }
103 }),
104})