|
| 1 | +import { useQuery, useQueryClient } from '@tanstack/react-query' |
| 2 | +import { todoOptions, todosOptions } from './queries' |
| 3 | + |
| 4 | +// ✅ passes: consuming imported queryOptions result directly |
| 5 | +export function Todos() { |
| 6 | + const query = useQuery(todosOptions) |
| 7 | + return query.data |
| 8 | +} |
| 9 | + |
| 10 | +// ✅ passes: spreading imported queryOptions result with additional options |
| 11 | +export function Todo({ id }: { id: string }) { |
| 12 | + const query = useQuery({ |
| 13 | + ...todoOptions(id), |
| 14 | + select: (data) => data.title, |
| 15 | + }) |
| 16 | + return query.data |
| 17 | +} |
| 18 | + |
| 19 | +// ✅ passes: referencing queryKey from imported queryOptions result |
| 20 | +export function invalidateTodos() { |
| 21 | + const queryClient = useQueryClient() |
| 22 | + queryClient.invalidateQueries({ queryKey: todosOptions.queryKey }) |
| 23 | +} |
| 24 | + |
| 25 | +// ❌ fails: inline queryKey + queryFn should use queryOptions() |
| 26 | +export function TodosBad() { |
| 27 | + const query = useQuery( |
| 28 | + // eslint-disable-next-line @tanstack/query/prefer-query-options -- Prefer using queryOptions() or infiniteQueryOptions() to co-locate queryKey and queryFn. |
| 29 | + { |
| 30 | + queryKey: ['todos'], |
| 31 | + queryFn: () => fetch('/api/todos').then((r) => r.json()), |
| 32 | + }, |
| 33 | + ) |
| 34 | + return query.data |
| 35 | +} |
| 36 | + |
| 37 | +// ❌ fails: inline queryKey should reference queryOptions result |
| 38 | +export function InvalidateTodosBad() { |
| 39 | + const queryClient = useQueryClient() |
| 40 | + // eslint-disable-next-line @tanstack/query/prefer-query-options -- Prefer referencing a queryKey from a queryOptions() result instead of typing it manually. |
| 41 | + queryClient.invalidateQueries({ queryKey: ['todos'] }) |
| 42 | +} |
| 43 | + |
| 44 | +// ❌ fails: inline queryKey as direct parameter |
| 45 | +export function GetTodosDataBad() { |
| 46 | + const queryClient = useQueryClient() |
| 47 | + // eslint-disable-next-line @tanstack/query/prefer-query-options -- Prefer referencing a queryKey from a queryOptions() result instead of typing it manually. |
| 48 | + return queryClient.getQueryData(['todos']) |
| 49 | +} |
0 commit comments