Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

prefer-query-options-demo.tsx

49 lines1.8 KB

1import { useQuery, useQueryClient } from '@tanstack/react-query'
2import { todoOptions, todosOptions } from './queries'
3​
4// βœ… passes: consuming imported queryOptions result directly
5export function Todos() {
6 const query = useQuery(todosOptions)
7 return query.data
8}
9​
10// βœ… passes: spreading imported queryOptions result with additional options
11export function Todo({ id }: { id: string }) {
12 const query = useQuery({
13 ...todoOptions(id),
14 select: (data) => data.title,
15 })
16 return query.data
18​
19// βœ… passes: referencing queryKey from imported queryOptions result
20export function invalidateTodos() {
21 const queryClient = useQueryClient()
22 queryClient.invalidateQueries({ queryKey: todosOptions.queryKey })
24​
25// ❌ fails: inline queryKey + queryFn should use queryOptions()
26export 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
36​
37// ❌ fails: inline queryKey should reference queryOptions result
38export 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'] })
43​
44// ❌ fails: inline queryKey as direct parameter
45export 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'])