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

query-options.md

34 lines1.1 KB

1---
2id: query-options
3title: Query Options
4---
5​
6One of the best ways to share `queryKey` and `queryFn` between multiple places, yet keep them co-located to one another, is to use the `queryOptions` helper. At runtime, this helper just returns whatever you pass into it, but it has a lot of advantages when using it [with TypeScript](../../typescript#typing-query-options). You can define all possible options for a query in one place, and you'll also get type inference and type safety for all of them.
7​
8[//]: # 'Example1'
9​
10```ts
11import { queryOptions } from '@tanstack/react-query'
12​
13function groupOptions(id: number) {
14 return queryOptions({
15 queryKey: ['groups', id],
16 queryFn: () => fetchGroups(id),
17 staleTime: 5 * 1000,
18 })
20​
21// usage:
22​
23useQuery(groupOptions(1))
24useSuspenseQuery(groupOptions(5))
25useQueries({
26 queries: [groupOptions(1), groupOptions(2)],
27})
28queryClient.prefetchQuery(groupOptions(23))
29queryClient.setQueryData(groupOptions(42).queryKey, newGroups)
30```
31​
32[//]: # 'Example1'
33​
34For Infinite Queries, a separate `infiniteQueryOptions` helper is available.