Skip to content

feat(eslint-plugin-query): add prefer-query-options rule#10359

Merged
Newbie012 merged 8 commits intomainfrom
feat-eslint-prefer-query-options
Mar 31, 2026
Merged

feat(eslint-plugin-query): add prefer-query-options rule#10359
Newbie012 merged 8 commits intomainfrom
feat-eslint-prefer-query-options

Conversation

@Newbie012
Copy link
Copy Markdown
Collaborator

@Newbie012 Newbie012 commented Mar 30, 2026

Prior discussion #8515

🎯 Changes

New ESLint rule prefer-query-options that enforces using queryOptions() / infiniteQueryOptions() to co-locate query keys and functions. A query key should be defined exactly once — the rule flags every place where a user types one manually.

This is rule is stricter and more opinionated than the others, I also createdrecommendedStrict config (flat/recommended-strict) which includes all recommended rules plus this rule.

Examples:

// 🔴 Inline queryKey + queryFn — should use queryOptions()
useQuery({
  queryKey: ['todos'],
  queryFn: () => fetchTodos(),
})

// 🔴 Inline queryKey in queryClient methods
queryClient.getQueryData(['todos'])
queryClient.invalidateQueries({ queryKey: ['todos'] })

// 🟢 Co-located via queryOptions()
const todosOptions = queryOptions({
  queryKey: ['todos'],
  queryFn: () => fetchTodos(),
})

useQuery(todosOptions)
useQuery({ ...todosOptions, select: (data) => data.items })
queryClient.getQueryData(todosOptions.queryKey)
queryClient.invalidateQueries({ queryKey: todosOptions.queryKey })

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested this code locally with pnpm run test:pr.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Summary by CodeRabbit

  • New Features

    • Added a new ESLint rule enforcing use of queryOptions and a "recommended strict" preset that enables it.
  • Documentation

    • Added a detailed docs page, navigation entry, and config examples showing correct/incorrect patterns and setup.
  • Tests

    • Added extensive test coverage validating allowed and violating scenarios.
  • Examples

    • Added demo examples illustrating correct usage and suppressed violations.
  • Chores

    • Added a changeset for a minor package bump.

@github-actions github-actions bot added documentation Improvements or additions to documentation package: eslint-plugin-query labels Mar 30, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 30, 2026

📝 Walkthrough

Walkthrough

Adds a new ESLint rule prefer-query-options with implementation, tests, docs, demo examples, a changeset, and new plugin exports/configs (recommendedStrict and flat/recommended-strict) to enable the rule.

Changes

Cohort / File(s) Summary
Release Metadata
\.changeset/prefer-query-options-rule.md
New changeset declaring a minor bump for @tanstack/eslint-plugin-query and announcing prefer-query-options and recommendedStrict.
Documentation
docs/config.json, docs/eslint/eslint-plugin-query.md, docs/eslint/prefer-query-options.md
Added nav entry and docs: new "Prefer Query Options" rule page, and "recommended strict" config docs for flat and legacy ESLint usage.
Rule Implementation
packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts
New ESLint rule detecting inline queryKey/queryFn in hooks, useQueries variants (including mapped returns), useIsFetching, and QueryClient calls; reports usage that should use queryOptions()/infiniteQueryOptions().
Rule Registration & Plugin Exports
packages/eslint-plugin-query/src/rules.ts, packages/eslint-plugin-query/src/index.ts
Registered the new rule; added recommendedStrict and flat/recommended-strict configs and corresponding Plugin interface entries; factored recommended rules into shared constants.
Tests
packages/eslint-plugin-query/src/__tests__/prefer-query-options.test.ts
Comprehensive RuleTester suite with allowed/forbidden cases across hooks, useQueries mappings, query client methods, edge cases, and expected messages/fixability.
Examples / Demo
examples/react/eslint-plugin-demo/eslint.config.js, examples/react/eslint-plugin-demo/src/queries.tsx, examples/react/eslint-plugin-demo/src/prefer-query-options-demo.tsx
Switched demo config to flat/recommended-strict; added queries.tsx exporting queryOptions builders and a demo prefer-query-options-demo.tsx showing compliant and lint-suppressed violating examples.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇 I hop through code and sniff each line,

Bundling keys and funcs so queries align.
No inline tangles, no mix-and-match fights,
Options bundled snugly — oh what delights!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding a new ESLint rule prefer-query-options to the eslint-plugin-query package.
Description check ✅ Passed The description comprehensively covers the changes, includes prior discussion context, provides clear examples of allowed and disallowed patterns, and confirms all checklist items are completed including testing and changeset creation.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat-eslint-prefer-query-options

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@nx-cloud
Copy link
Copy Markdown

nx-cloud bot commented Mar 30, 2026

View your CI Pipeline Execution ↗ for commit 87d26cf

Command Status Duration Result
nx run-many --target=build --exclude=examples/*... ✅ Succeeded <1s View ↗
nx affected --targets=test:sherif,test:knip,tes... ✅ Succeeded 10s View ↗

☁️ Nx Cloud last updated this comment at 2026-03-31 10:08:30 UTC

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Mar 30, 2026

🚀 Changeset Version Preview

1 package(s) bumped directly, 23 bumped as dependents.

🟨 Minor bumps

Package Version Reason
@tanstack/eslint-plugin-query 5.95.2 → 5.96.0 Changeset
@tanstack/angular-query-experimental 5.95.2 → 5.96.0 Dependent
@tanstack/angular-query-persist-client 5.95.2 → 5.96.0 Dependent
@tanstack/preact-query 5.95.2 → 5.96.0 Dependent
@tanstack/preact-query-devtools 5.95.2 → 5.96.0 Dependent
@tanstack/preact-query-persist-client 5.95.2 → 5.96.0 Dependent
@tanstack/query-async-storage-persister 5.95.2 → 5.96.0 Dependent
@tanstack/query-broadcast-client-experimental 5.95.2 → 5.96.0 Dependent
@tanstack/query-core 5.95.2 → 5.96.0 Dependent
@tanstack/query-devtools 5.95.2 → 5.96.0 Dependent
@tanstack/query-persist-client-core 5.95.2 → 5.96.0 Dependent
@tanstack/query-sync-storage-persister 5.95.2 → 5.96.0 Dependent
@tanstack/react-query 5.95.2 → 5.96.0 Dependent
@tanstack/react-query-devtools 5.95.2 → 5.96.0 Dependent
@tanstack/react-query-next-experimental 5.95.2 → 5.96.0 Dependent
@tanstack/react-query-persist-client 5.95.2 → 5.96.0 Dependent
@tanstack/solid-query 5.95.2 → 5.96.0 Dependent
@tanstack/solid-query-devtools 5.95.2 → 5.96.0 Dependent
@tanstack/solid-query-persist-client 5.95.2 → 5.96.0 Dependent
@tanstack/vue-query 5.95.2 → 5.96.0 Dependent

🟩 Patch bumps

Package Version Reason
@tanstack/svelte-query 6.1.10 → 6.1.11 Dependent
@tanstack/svelte-query-devtools 6.1.10 → 6.1.11 Dependent
@tanstack/svelte-query-persist-client 6.1.10 → 6.1.11 Dependent
@tanstack/vue-query-devtools 6.1.10 → 6.1.11 Dependent

@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new bot commented Mar 30, 2026

More templates

@tanstack/angular-query-experimental

npm i https://pkg.pr.new/@tanstack/angular-query-experimental@10359

@tanstack/eslint-plugin-query

npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@10359

@tanstack/preact-query

npm i https://pkg.pr.new/@tanstack/preact-query@10359

@tanstack/preact-query-devtools

npm i https://pkg.pr.new/@tanstack/preact-query-devtools@10359

@tanstack/preact-query-persist-client

npm i https://pkg.pr.new/@tanstack/preact-query-persist-client@10359

@tanstack/query-async-storage-persister

npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@10359

@tanstack/query-broadcast-client-experimental

npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@10359

@tanstack/query-core

npm i https://pkg.pr.new/@tanstack/query-core@10359

@tanstack/query-devtools

npm i https://pkg.pr.new/@tanstack/query-devtools@10359

@tanstack/query-persist-client-core

npm i https://pkg.pr.new/@tanstack/query-persist-client-core@10359

@tanstack/query-sync-storage-persister

npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@10359

@tanstack/react-query

npm i https://pkg.pr.new/@tanstack/react-query@10359

@tanstack/react-query-devtools

npm i https://pkg.pr.new/@tanstack/react-query-devtools@10359

@tanstack/react-query-next-experimental

npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@10359

@tanstack/react-query-persist-client

npm i https://pkg.pr.new/@tanstack/react-query-persist-client@10359

@tanstack/solid-query

npm i https://pkg.pr.new/@tanstack/solid-query@10359

@tanstack/solid-query-devtools

npm i https://pkg.pr.new/@tanstack/solid-query-devtools@10359

@tanstack/solid-query-persist-client

npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@10359

@tanstack/svelte-query

npm i https://pkg.pr.new/@tanstack/svelte-query@10359

@tanstack/svelte-query-devtools

npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@10359

@tanstack/svelte-query-persist-client

npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@10359

@tanstack/vue-query

npm i https://pkg.pr.new/@tanstack/vue-query@10359

@tanstack/vue-query-devtools

npm i https://pkg.pr.new/@tanstack/vue-query-devtools@10359

commit: 87d26cf

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Mar 30, 2026

size-limit report 📦

Path Size
react full 11.98 KB (0%)
react minimal 9.01 KB (0%)

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/eslint/prefer-query-options.md`:
- Around line 27-31: The examples (e.g., useFooQuery and the queryOptions(...)
snippets) reference id without any binding; change them into factory functions
that accept id (e.g., function useFooQuery(id) or export function
queryOptions(id)) and then pass that id into the useQuery call (or into
queryOptions(id)) so the id is in scope; update any example that builds
queryOptions(...) to be queryOptions(id) and update callers to pass the id into
useFooQuery or the options factory accordingly (references: useFooQuery,
queryOptions, options).

In
`@packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts`:
- Around line 23-30: The rule currently only flags inline options for methods in
queryClientOptionMethods but misses the newer APIs; add 'query' and
'infiniteQuery' to the queryClientOptionMethods array so inline options passed
to queryClient.query(...) and queryClient.infiniteQuery(...) are checked, and
update the test suite for this rule to include invalid cases covering query()
and infiniteQuery() (matching the existing invalid cases for
fetchQuery/fetchInfiniteQuery) so the select option behavior is asserted for
both legacy and new APIs; update any test matrix entries that reference method
names to include 'query' and 'infiniteQuery' as well.
- Around line 177-180: The rule currently checks options.type ===
AST_NODE_TYPES.ArrayExpression directly and misses TS assertion wrappers; update
the checks inside the prefer-query-options rule where queryClientQueryKeyMethods
is handled (and inside hasInlineFilterQueryKey) to first unwrap TypeScript
assertion nodes using the existing helper dereferenceVariablesAndTypeAssertions
(as used in exhaustive-deps.rule.ts) and then check the resulting node.type ===
AST_NODE_TYPES.ArrayExpression; add tests covering both "as const"
(TSAsExpression) and "satisfies" (TSSatisfiesExpression) forms to ensure these
assertion-wrapped array literals are recognized.
- Around line 75-76: The rule must stop relying on raw identifier text and
instead resolve symbols via import specifiers and scope bindings: update places
using isIdentifierWithOneOfNames, isIdentifierWithName, and the
queryClientVariables Set to resolve the node's binding (use
context.getScope()/sourceCode.getScope or eslint-utils findVariable) and then
verify the binding originates from a TanStack import via
helpers.isTanstackQueryImport by checking the ImportSpecifier/ImportDeclaration
and the imported.name (e.g., 'useQuery', 'useQueryClient', 'QueryClient'); when
tracking QueryClient results store the actual Variable/binding or the
ImportSpecifier reference instead of a string so membership checks are
scope-aware and won’t match shadowed parameters, and for aliased imports compare
the import specifier's imported.name to the canonical TanStack symbol names
rather than the local identifier text.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3697aff5-b7ea-4d4f-a1de-925c4b9f3ac8

📥 Commits

Reviewing files that changed from the base of the PR and between 7e5fe21 and 3a8e0f4.

📒 Files selected for processing (8)
  • .changeset/prefer-query-options-rule.md
  • docs/config.json
  • docs/eslint/eslint-plugin-query.md
  • docs/eslint/prefer-query-options.md
  • packages/eslint-plugin-query/src/__tests__/prefer-query-options.test.ts
  • packages/eslint-plugin-query/src/index.ts
  • packages/eslint-plugin-query/src/rules.ts
  • packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts`:
- Around line 78-94: The rule currently inspects nodes directly and misses
patterns wrapped in TypeScript assertions/satisfies; update
reportInlineQueryOptions and reportInlineFilterQueryKey to first call
unwrapTypeAssertions(node) and use the unwrapped node for
ASTUtils.isObjectExpression checks and subsequent
hasInlineQueryOptions/hasInlineFilterQueryKey evaluations, and likewise apply
unwrapTypeAssertions when traversing queries entries (the logic around the
queries array that checks each entry) so that asserted/satisfied
ObjectExpression/ArrayExpression forms are detected; keep existing messageIds
and only change the inspected node to the unwrapped result.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3e887bb9-56cc-4d8e-be48-9e9b47c3ca38

📥 Commits

Reviewing files that changed from the base of the PR and between 3a8e0f4 and 26737a2.

📒 Files selected for processing (3)
  • docs/eslint/prefer-query-options.md
  • packages/eslint-plugin-query/src/__tests__/prefer-query-options.test.ts
  • packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts
✅ Files skipped from review due to trivial changes (1)
  • docs/eslint/prefer-query-options.md

Comment on lines +78 to +94
function reportInlineQueryOptions(node: TSESTree.Node): void {
if (ASTUtils.isObjectExpression(node) && hasInlineQueryOptions(node)) {
context.report({
node,
messageId: 'preferQueryOptions',
})
}
}

function reportInlineFilterQueryKey(node: TSESTree.Node): void {
if (ASTUtils.isObjectExpression(node) && hasInlineFilterQueryKey(node)) {
context.report({
node,
messageId: 'preferQueryOptionsQueryKey',
})
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, locate and examine the target file
fd -t f "prefer-query-options.rule.ts" packages/eslint-plugin-query

Repository: TanStack/query

Length of output: 146


🏁 Script executed:

# Get the file size to determine how to read it
wc -l packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts

Repository: TanStack/query

Length of output: 150


🏁 Script executed:

# Read the entire file to understand the implementation
cat -n packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts

Repository: TanStack/query

Length of output: 12438


🏁 Script executed:

# Find test files for this rule
fd -t f "prefer-query-options" packages/eslint-plugin-query/src/rules --type f

Repository: TanStack/query

Length of output: 146


🏁 Script executed:

# Look for test directory
fd -t d "__tests__" packages/eslint-plugin-query/src/rules/prefer-query-options/

Repository: TanStack/query

Length of output: 40


🏁 Script executed:

# Find test files more broadly
fd "prefer-query-options" packages/eslint-plugin-query -type f | grep -i test

Repository: TanStack/query

Length of output: 228


🏁 Script executed:

# Look for test files in the rules directory
find packages/eslint-plugin-query -name "*prefer-query-options*" -type f

Repository: TanStack/query

Length of output: 218


🏁 Script executed:

# Read the test file
cat -n packages/eslint-plugin-query/src/__tests__/prefer-query-options.test.ts

Repository: TanStack/query

Length of output: 39919


🏁 Script executed:

# Double-check the exact line ranges mentioned in the review comment
# Lines 124-127 (queriesHooks handling)
sed -n '124,127p' packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts

Repository: TanStack/query

Length of output: 186


🏁 Script executed:

# Lines 210-288 (getReturnedObjectExpressions and getQueryObjects)
sed -n '210,288p' packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts

Repository: TanStack/query

Length of output: 2039


🏁 Script executed:

# Verify unwrapTypeAssertions implementation
sed -n '379,389p' packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts

Repository: TanStack/query

Length of output: 347


Unwrap asserted option objects before inspecting them.

unwrapTypeAssertions() only protects raw query-key arrays. Patterns like useQuery({ queryKey: ['todos'], queryFn: () => fetchTodos() } as const), queryClient.fetchQuery({ ... } satisfies SomeOptions), and useQueries({ queries: ([{ ... }] as const) }) bypass the rule because these paths still require a bare ObjectExpression/ArrayExpression. Add unwrapping before object checks and while traversing queries entries.

Suggested fix
     function reportInlineQueryOptions(node: TSESTree.Node): void {
-      if (ASTUtils.isObjectExpression(node) && hasInlineQueryOptions(node)) {
+      const expression = unwrapTypeAssertions(node)
+      if (
+        ASTUtils.isObjectExpression(expression) &&
+        hasInlineQueryOptions(expression)
+      ) {
         context.report({
           node,
           messageId: 'preferQueryOptions',
         })
       }
     }

     function reportInlineFilterQueryKey(node: TSESTree.Node): void {
-      if (ASTUtils.isObjectExpression(node) && hasInlineFilterQueryKey(node)) {
+      const expression = unwrapTypeAssertions(node)
+      if (
+        ASTUtils.isObjectExpression(expression) &&
+        hasInlineFilterQueryKey(expression)
+      ) {
         context.report({
           node,
           messageId: 'preferQueryOptionsQueryKey',
         })
       }
     }
@@
-          if (
-            queriesHooks.includes(importedName) &&
-            ASTUtils.isObjectExpression(options)
-          ) {
+          const expression = unwrapTypeAssertions(options)
+          if (
+            queriesHooks.includes(importedName) &&
+            ASTUtils.isObjectExpression(expression)
+          ) {
             const queries = ASTUtils.findPropertyWithIdentifierKey(
-              options.properties,
+              expression.properties,
               'queries',
             )?.value
@@
 function getReturnedObjectExpressions(
   node: TSESTree.Node,
 ): Array<TSESTree.ObjectExpression> {
+  node = unwrapTypeAssertions(node)
+
   if (ASTUtils.isObjectExpression(node)) {
     return [node]
   }
@@
 function getQueryObjects(
   node: TSESTree.Node,
 ): Array<TSESTree.ObjectExpression> {
+  node = unwrapTypeAssertions(node)
+
   if (node.type === AST_NODE_TYPES.ArrayExpression) {
-    return node.elements.flatMap((element) => {
-      if (element !== null && ASTUtils.isObjectExpression(element)) {
-        return [element]
-      }
-
-      return []
-    })
+    return node.elements.flatMap((element) =>
+      element === null ? [] : getReturnedObjectExpressions(element),
+    )
   }

Also applies to: 124-127, 210-288

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts`
around lines 78 - 94, The rule currently inspects nodes directly and misses
patterns wrapped in TypeScript assertions/satisfies; update
reportInlineQueryOptions and reportInlineFilterQueryKey to first call
unwrapTypeAssertions(node) and use the unwrapped node for
ASTUtils.isObjectExpression checks and subsequent
hasInlineQueryOptions/hasInlineFilterQueryKey evaluations, and likewise apply
unwrapTypeAssertions when traversing queries entries (the logic around the
queries array that checks each entry) so that asserted/satisfied
ObjectExpression/ArrayExpression forms are detected; keep existing messageIds
and only change the inspected node to the unwrapped result.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
packages/eslint-plugin-query/src/__tests__/prefer-query-options.test.ts (2)

45-130: Add direct and mapped builder happy paths.

The valid hook matrix covers identifiers and wrapper calls, but it still doesn't lock down useQuery(queryOptions(...)) or mapped builder results for useQueries / useSuspenseQueries. Those are common migration shapes for this rule, so a false positive there would still pass the suite.

Suggested additions
       valid: [
         {
           name: 'useQuery with queryOptions result is allowed',
           code: normalizeIndent`
             import { useQuery, queryOptions } from '@tanstack/react-query'

             const todosOptions = queryOptions({
               queryKey: ['todos'],
               queryFn: () => fetchTodos(),
             })

             function Component() {
               const query = useQuery(todosOptions)
               return null
             }
           `,
         },
+        {
+          name: 'useQuery with inline queryOptions call is allowed',
+          code: normalizeIndent`
+            import { useQuery, queryOptions } from '@tanstack/react-query'
+
+            function Component() {
+              const query = useQuery(
+                queryOptions({
+                  queryKey: ['todos'],
+                  queryFn: () => fetchTodos(),
+                }),
+              )
+              return null
+            }
+          `,
+        },
         {
           name: 'useQueries with all entries from queryOptions is allowed',
           code: normalizeIndent`
             import { useQueries } from '@tanstack/react-query'

             function Component() {
               const queries = useQueries({
                 queries: [todosOptions, usersOptions],
               })
               return null
             }
           `,
         },
+        {
+          name: 'useQueries with mapped queryOptions results is allowed',
+          code: normalizeIndent`
+            import { useQueries } from '@tanstack/react-query'
+
+            function Component({ ids }) {
+              const queries = useQueries({
+                queries: ids.map((id) => getTodoOptions(id)),
+              })
+              return null
+            }
+          `,
+        },
+        {
+          name: 'useSuspenseQueries with mapped queryOptions results is allowed',
+          code: normalizeIndent`
+            import { useSuspenseQueries } from '@tanstack/react-query'
+
+            function Component({ ids }) {
+              const queries = useSuspenseQueries({
+                queries: ids.map((id) => getTodoOptions(id)),
+              })
+              return null
+            }
+          `,
+        },
       ],
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/eslint-plugin-query/src/__tests__/prefer-query-options.test.ts`
around lines 45 - 130, Add happy-path tests to cover direct and mapped builder
usages so the rule doesn't false-positive: add a valid case where useQuery is
called directly with a queryOptions call (e.g., useQuery(queryOptions({...}))
and a valid case where useQueries / useSuspenseQueries receive mapped builder
results (e.g., queries: [todosOptions, usersOptions].map(... ) or queries:
[todosOptions(), usersOptions()]). Update the test block under "hooks consuming
queryOptions result" in prefer-query-options.test.ts to include these scenarios
(referencing useQuery, useQueries, useSuspenseQueries, queryOptions,
todosOptions, usersOptions) as additional entries in the valid array.

659-767: Add matching happy paths for client methods that take full options.

fetchQuery, prefetchQuery, and the ensure* methods are only asserted in the failing inline-object form. Adding a shared-options happy path would protect the rule's intended replacement pattern on the queryClient side too.

Suggested additions
       valid: [
         {
           name: 'queryClient.getQueryData with options.queryKey is allowed',
           code: normalizeIndent`
             import { useQueryClient, queryOptions } from '@tanstack/react-query'

             const todosOptions = queryOptions({
               queryKey: ['todos'],
               queryFn: () => fetchTodos(),
             })

             function Component() {
               const queryClient = useQueryClient()
               const data = queryClient.getQueryData(todosOptions.queryKey)
               return null
             }
           `,
         },
+        {
+          name: 'queryClient.fetchQuery with queryOptions result is allowed',
+          code: normalizeIndent`
+            import { useQueryClient, queryOptions } from '@tanstack/react-query'
+
+            const todosOptions = queryOptions({
+              queryKey: ['todos'],
+              queryFn: () => fetchTodos(),
+            })
+
+            function Component() {
+              const queryClient = useQueryClient()
+              queryClient.fetchQuery(todosOptions)
+              return null
+            }
+          `,
+        },
+        {
+          name: 'queryClient.fetchInfiniteQuery with builder call result is allowed',
+          code: normalizeIndent`
+            import { useQueryClient } from '@tanstack/react-query'
+
+            function Component({ id }) {
+              const queryClient = useQueryClient()
+              queryClient.fetchInfiniteQuery(getTodoPagesOptions(id))
+              return null
+            }
+          `,
+        },
       ],
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/eslint-plugin-query/src/__tests__/prefer-query-options.test.ts`
around lines 659 - 767, Add matching "happy path" valid tests for the
queryClient methods that accept full options so the rule verifies the allowed
replacement pattern; specifically add valid cases for fetchQuery, prefetchQuery,
fetchInfiniteQuery, prefetchInfiniteQuery, ensureQueryData, and
ensureInfiniteQueryData that demonstrate the accepted "shared/options" usage
(the intended replacement for the inline { queryKey, queryFn } pattern) so the
rule's client-side behavior is covered alongside the current invalid tests that
reference those methods.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/eslint-plugin-query/src/__tests__/prefer-query-options.test.ts`:
- Around line 45-130: Add happy-path tests to cover direct and mapped builder
usages so the rule doesn't false-positive: add a valid case where useQuery is
called directly with a queryOptions call (e.g., useQuery(queryOptions({...}))
and a valid case where useQueries / useSuspenseQueries receive mapped builder
results (e.g., queries: [todosOptions, usersOptions].map(... ) or queries:
[todosOptions(), usersOptions()]). Update the test block under "hooks consuming
queryOptions result" in prefer-query-options.test.ts to include these scenarios
(referencing useQuery, useQueries, useSuspenseQueries, queryOptions,
todosOptions, usersOptions) as additional entries in the valid array.
- Around line 659-767: Add matching "happy path" valid tests for the queryClient
methods that accept full options so the rule verifies the allowed replacement
pattern; specifically add valid cases for fetchQuery, prefetchQuery,
fetchInfiniteQuery, prefetchInfiniteQuery, ensureQueryData, and
ensureInfiniteQueryData that demonstrate the accepted "shared/options" usage
(the intended replacement for the inline { queryKey, queryFn } pattern) so the
rule's client-side behavior is covered alongside the current invalid tests that
reference those methods.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 035de3d3-cacd-4f1c-8d05-338c4db141b8

📥 Commits

Reviewing files that changed from the base of the PR and between aec9ed5 and c46f6fe.

📒 Files selected for processing (1)
  • packages/eslint-plugin-query/src/__tests__/prefer-query-options.test.ts

@Newbie012 Newbie012 merged commit ed2f2ab into main Mar 31, 2026
8 checks passed
@Newbie012 Newbie012 deleted the feat-eslint-prefer-query-options branch March 31, 2026 10:13
@github-actions github-actions bot mentioned this pull request Mar 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation package: eslint-plugin-query

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants