Skip to content

feat(eslint): add type-checked configuration for eslint plugin #8966

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions docs/eslint/eslint-plugin-query.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,21 @@ export default [
]
```

### Recommended type-checked setup

If you're using TypeScript and want to enable rules that require type information, you can use the `flat/recommendedTypeChecked` config:

```js
import pluginQuery from '@tanstack/eslint-plugin-query'

export default [
...pluginQuery.configs['flat/recommendedTypeChecked'],
// Any other config...
]
```

> ℹ️ This setup requires type-aware linting. You can follow the [TypeScript ESLint documentation on type-checking](https://typescript-eslint.io/linting/typed-linting/) to set up your ESLint config accordingly.

### Custom setup

Alternatively, you can load the plugin and configure only the rules you want to use:
Expand Down
1 change: 1 addition & 0 deletions docs/eslint/no-void-query-fn.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,5 @@ useQuery({
## Attributes

- [x] ✅ Recommended
- [x] 💭 Type checked
- [ ] 🔧 Fixable
27 changes: 27 additions & 0 deletions examples/react/eslint-type-checked/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

pnpm-lock.yaml
yarn.lock
package-lock.json

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
6 changes: 6 additions & 0 deletions examples/react/eslint-type-checked/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Example

To run this example:

- `npm install`
- `npm run dev`
20 changes: 20 additions & 0 deletions examples/react/eslint-type-checked/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// @ts-check

import eslint from '@eslint/js'
import tseslint from 'typescript-eslint'
import pluginQuery from '@tanstack/eslint-plugin-query'

export default tseslint.config(
eslint.configs.recommended,
tseslint.configs.recommended,
pluginQuery.configs['flat/recommendedTypeChecked'],
{
files: ['**/*.ts', '**/*.tsx'],
languageOptions: {
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
)
16 changes: 16 additions & 0 deletions examples/react/eslint-type-checked/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" type="image/svg+xml" href="/emblem-light.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />

<title>TanStack Query React Basic Example App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="module" src="/src/index.tsx"></script>
</body>
</html>
26 changes: 26 additions & 0 deletions examples/react/eslint-type-checked/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "@tanstack/query-example-react-eslint-type-checked",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@tanstack/query-sync-storage-persister": "^5.71.10",
"@tanstack/react-query": "^5.71.10",
"@tanstack/react-query-devtools": "^5.71.10",
"@tanstack/react-query-persist-client": "^5.71.10",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@tanstack/eslint-plugin-query": "^5.71.5",
"@types/react": "^18.2.79",
"@types/react-dom": "^18.2.25",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "5.8.2",
"vite": "^6.2.4"
}
}
13 changes: 13 additions & 0 deletions examples/react/eslint-type-checked/public/emblem-light.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
161 changes: 161 additions & 0 deletions examples/react/eslint-type-checked/src/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import * as React from 'react'
import ReactDOM from 'react-dom/client'
import { QueryClient, useQuery, useQueryClient } from '@tanstack/react-query'
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'

const queryClient = new QueryClient({
defaultOptions: {
queries: {
gcTime: 1000 * 60 * 60 * 24, // 24 hours
},
},
})

const persister = createSyncStoragePersister({
storage: window.localStorage,
})

type Post = {
id: number
title: string
body: string
}

function usePosts() {
return useQuery({
queryKey: ['posts'],
queryFn: async (): Promise<Array<Post>> => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts')
return await response.json()
},
})
}

function Posts({
setPostId,
}: {
setPostId: React.Dispatch<React.SetStateAction<number>>
}) {
const queryClient = useQueryClient()
const { status, data, error, isFetching } = usePosts()

return (
<div>
<h1>Posts</h1>
<div>
{status === 'pending' ? (
'Loading...'
) : status === 'error' ? (
<span>Error: {error.message}</span>
) : (
<>
<div>
{data.map((post) => (
<p key={post.id}>
<a
onClick={() => setPostId(post.id)}
href="#"
style={
// We can access the query data here to show bold links for
// ones that are cached
queryClient.getQueryData(['post', post.id])
? {
fontWeight: 'bold',
color: 'green',
}
: {}
}
>
{post.title}
</a>
</p>
))}
</div>
<div>{isFetching ? 'Background Updating...' : ' '}</div>
</>
)}
</div>
</div>
)
}

const getPostById = async (id: number): Promise<Post> => {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts/${id}`,
)
return await response.json()
}

function usePost(postId: number) {
return useQuery({
queryKey: ['post', postId],
queryFn: () => getPostById(postId),
enabled: !!postId,
})
}

function Post({
postId,
setPostId,
}: {
postId: number
setPostId: React.Dispatch<React.SetStateAction<number>>
}) {
const { status, data, error, isFetching } = usePost(postId)

return (
<div>
<div>
<a onClick={() => setPostId(-1)} href="#">
Back
</a>
</div>
{!postId || status === 'pending' ? (
'Loading...'
) : status === 'error' ? (
<span>Error: {error.message}</span>
) : (
<>
<h1>{data.title}</h1>
<div>
<p>{data.body}</p>
</div>
<div>{isFetching ? 'Background Updating...' : ' '}</div>
</>
)}
</div>
)
}

function App() {
const [postId, setPostId] = React.useState(-1)

return (
<PersistQueryClientProvider
client={queryClient}
persistOptions={{ persister }}
>
<p>
As you visit the posts below, you will notice them in a loading state
the first time you load them. However, after you return to this list and
click on any posts you have already visited again, you will see them
load instantly and background refresh right before your eyes!{' '}
<strong>
(You may need to throttle your network speed to simulate longer
loading sequences)
</strong>
</p>
{postId > -1 ? (
<Post postId={postId} setPostId={setPostId} />
) : (
<Posts setPostId={setPostId} />
)}
<ReactQueryDevtools initialIsOpen />
</PersistQueryClientProvider>
)
}

const rootElement = document.getElementById('root') as HTMLElement
ReactDOM.createRoot(rootElement).render(<App />)
24 changes: 24 additions & 0 deletions examples/react/eslint-type-checked/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,

/* Bundler mode */
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src", "eslint.config.js", "vite.config.ts"]
}
6 changes: 6 additions & 0 deletions examples/react/eslint-type-checked/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
plugins: [react()],
})
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ RuleTester.afterAll = afterAll
RuleTester.describe = describe
RuleTester.it = it

const ruleTester = new RuleTester({
const ruleTesterTypeChecked = new RuleTester({
languageOptions: {
parser: await import('@typescript-eslint/parser'),
parserOptions: {
Expand All @@ -18,7 +18,7 @@ const ruleTester = new RuleTester({
},
})

ruleTester.run('no-void-query-fn', rule, {
ruleTesterTypeChecked.run('no-void-query-fn', rule, {
valid: [
{
name: 'queryFn returns a value',
Expand Down Expand Up @@ -323,3 +323,31 @@ ruleTester.run('no-void-query-fn', rule, {
},
],
})

const ruleTester = new RuleTester({
languageOptions: {
parser: await import('@typescript-eslint/parser'),
},
})

ruleTester.run('no-void-query-fn with no program', rule, {
valid: [],
invalid: [
{
name: 'queryFn returns void',
code: normalizeIndent`
import { useQuery } from '@tanstack/react-query'
function Component() {
const query = useQuery({
queryKey: ['test'],
queryFn: () => {
console.log('test')
},
})
return null
}
`,
errors: [{ messageId: 'noProgram' }],
},
],
})
Loading