Open History to see the last commit
1import { AST_NODE_TYPES, ESLintUtils } from '@typescript-eslint/utils'
2import { getDocsUrl } from '../../utils/get-docs-url'
3import { ASTUtils } from '../../utils/ast-utils'
4import { detectTanstackQueryImports } from '../../utils/detect-react-query-imports'
5import { NoRestDestructuringUtils } from './no-rest-destructuring.utils'
6import type { ExtraRuleDocs } from '../../types'
7β
8export const name = 'no-rest-destructuring'
9β
10const queryHooks = [
11 'useQuery',
12 'useQueries',
13 'useInfiniteQuery',
14 'useSuspenseQuery',
15 'useSuspenseQueries',
16 'useSuspenseInfiniteQuery',
17]
18β
19const createRule = ESLintUtils.RuleCreator<ExtraRuleDocs>(getDocsUrl)
20β
21export const rule = createRule({
22 name,
23 meta: {
24 type: 'problem',
25 docs: {
26 description: 'Disallows rest destructuring in queries',
27 recommended: 'warn',
28 },
29 messages: {
30 objectRestDestructure: `Object rest destructuring on a query will observe all changes to the query, leading to excessive re-renders.`,
31 },
32 schema: [],
33 },
34 defaultOptions: [],
35β
36 create: detectTanstackQueryImports((context, _, helpers) => {
37 const queryResultVariables = new Set<string>()
38β
39 return {
40 CallExpression: (node) => {
41 if (
42 !ASTUtils.isIdentifierWithOneOfNames(node.callee, queryHooks) ||
43 node.parent.type !== AST_NODE_TYPES.VariableDeclarator ||
44 !helpers.isTanstackQueryImport(node.callee)
45 ) {
46 return
47 }
48β
49 const returnValue = node.parent.id
50β
51 if (
52 node.callee.name !== 'useQueries' &&
53 node.callee.name !== 'useSuspenseQueries'
54 ) {
55 if (NoRestDestructuringUtils.isObjectRestDestructuring(returnValue)) {
56 return context.report({
57 node: node.parent,
58 messageId: 'objectRestDestructure',
59 })
60 }
61β
62 if (returnValue.type === AST_NODE_TYPES.Identifier) {
63 queryResultVariables.add(returnValue.name)
64 }
65β
66 return
67 }
68β
69 if (returnValue.type !== AST_NODE_TYPES.ArrayPattern) {
70 if (returnValue.type === AST_NODE_TYPES.Identifier) {
71 queryResultVariables.add(returnValue.name)
72 }
73 return
74 }
75β
76 returnValue.elements.forEach((queryResult) => {
77 if (queryResult === null) {
78 return
79 }
80 if (NoRestDestructuringUtils.isObjectRestDestructuring(queryResult)) {
81 context.report({
82 node: queryResult,
83 messageId: 'objectRestDestructure',
84 })
85 }
86 })
87 },
88β
89 VariableDeclarator: (node) => {
90 if (
91 node.init?.type === AST_NODE_TYPES.Identifier &&
92 queryResultVariables.has(node.init.name) &&
93 NoRestDestructuringUtils.isObjectRestDestructuring(node.id)
94 ) {
95 context.report({
96 node,
97 messageId: 'objectRestDestructure',
98 })
99 }
100 },
101β
102 SpreadElement: (node) => {
103 if (
104 node.argument.type === AST_NODE_TYPES.Identifier &&
105 queryResultVariables.has(node.argument.name)
106 ) {
107 context.report({
108 node,
109 messageId: 'objectRestDestructure',
110 })
111 }
112 },
113 }
114 }),
115})