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

stable-query-client.rule.ts

78 lines2.2 KB

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