Skip to content

Commit

Permalink
fix(eslint-plugin-query): handle optional and non-null chaining in ex…
Browse files Browse the repository at this point in the history
…haustive-deps (#8365)

* fix: handle optional and non-null chaining in exhaustive-deps

Fixed a false positive in the exhaustive-deps rule when using optional chaining and non-null assertions in query keys and functions.

* ci: apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
  • Loading branch information
Newbie012 and autofix-ci[bot] authored Nov 28, 2024
1 parent dc4ae50 commit c402a2b
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
24 changes: 24 additions & 0 deletions packages/eslint-plugin-query/src/__tests__/exhaustive-deps.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,30 @@ ruleTester.run('exhaustive-deps', rule, {
};
`,
},
{
name: 'should pass with optional chaining as key',
code: `
function useTest(data?: any) {
return useQuery({
queryKey: ['query-name', data?.address],
queryFn: async () => sendQuery(data.address),
enabled: !!data?.address,
})
}
`,
},
{
name: 'should pass with optional chaining as key and non-null assertion in queryFn',
code: `
function useTest(data?: any) {
return useQuery({
queryKey: ['query-name', data?.address],
queryFn: async () => sendQuery(data!.address),
enabled: !!data?.address,
})
}
`,
},
],
invalid: [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,16 @@ export const rule = createRule({

const existingKeys = ASTUtils.getNestedIdentifiers(queryKeyNode).map(
(identifier) =>
ASTUtils.mapKeyNodeToText(identifier, context.sourceCode),
ASTUtils.mapKeyNodeToBaseText(identifier, context.sourceCode),
)

const missingRefs = relevantRefs
.map((ref) => ({
ref: ref,
text: ASTUtils.mapKeyNodeToText(ref.identifier, context.sourceCode),
text: ASTUtils.mapKeyNodeToBaseText(
ref.identifier,
context.sourceCode,
),
}))
.filter(({ ref, text }) => {
return (
Expand Down
10 changes: 10 additions & 0 deletions packages/eslint-plugin-query/src/utils/ast-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,10 +224,20 @@ export const ASTUtils = {
return sourceCode.getText(
ASTUtils.traverseUpOnly(node, [
AST_NODE_TYPES.MemberExpression,
AST_NODE_TYPES.TSNonNullExpression,
AST_NODE_TYPES.Identifier,
]),
)
},
mapKeyNodeToBaseText(
node: TSESTree.Node,
sourceCode: Readonly<TSESLint.SourceCode>,
) {
return ASTUtils.mapKeyNodeToText(node, sourceCode).replace(
/(\?\.|!\.)/g,
'.',
)
},
isValidReactComponentOrHookName(
identifier: TSESTree.Identifier | null | undefined,
) {
Expand Down

0 comments on commit c402a2b

Please sign in to comment.