0
# Query Operations
1
2
Core query functionality providing data fetching, caching, invalidation, and state management with automatic background updates and intelligent cache strategies.
3
4
## Capabilities
5
6
### Imperative Query Fetching
7
8
Direct query execution methods for fetching data outside of observers.
9
10
```typescript { .api }
11
/**
12
* Fetch a query imperatively and return the data
13
* Creates or reuses existing query in cache
14
* @param options - Query configuration including key and function
15
* @returns Promise resolving to query data
16
*/
17
fetchQuery<T>(options: FetchQueryOptions<T>): Promise<T>;
18
19
/**
20
* Prefetch a query without subscribing to it
21
* Useful for loading data before it's needed
22
* @param options - Query configuration including key and function
23
* @returns Promise that resolves when prefetch completes
24
*/
25
prefetchQuery<T>(options: FetchQueryOptions<T>): Promise<void>;
26
27
/**
28
* Ensure query data exists, fetching if necessary
29
* Won't refetch if data is fresh unless revalidateIfStale is true
30
* @param options - Query configuration with revalidation options
31
* @returns Promise resolving to existing or fetched data
32
*/
33
ensureQueryData<T>(options: EnsureQueryDataOptions<T>): Promise<T>;
34
35
interface FetchQueryOptions<T> {
36
queryKey: QueryKey;
37
queryFn?: QueryFunction<T>;
38
staleTime?: number;
39
gcTime?: number;
40
retry?: RetryValue<T>;
41
networkMode?: NetworkMode;
42
initialData?: T | InitialDataFunction<T>;
43
initialDataUpdatedAt?: number | (() => number | undefined);
44
meta?: QueryMeta;
45
signal?: AbortSignal;
46
}
47
48
interface EnsureQueryDataOptions<T> extends FetchQueryOptions<T> {
49
revalidateIfStale?: boolean;
50
}
51
```
52
53
**Usage Examples:**
54
55
```typescript
56
import { QueryClient } from "@tanstack/query-core";
57
58
const queryClient = new QueryClient();
59
60
// Basic fetch
61
const user = await queryClient.fetchQuery({
62
queryKey: ['user', 123],
63
queryFn: async () => {
64
const response = await fetch('/api/user/123');
65
return response.json();
66
},
67
});
68
69
// Prefetch for later use
70
await queryClient.prefetchQuery({
71
queryKey: ['posts', 'popular'],
72
queryFn: async () => {
73
const response = await fetch('/api/posts/popular');
74
return response.json();
75
},
76
staleTime: 5 * 60 * 1000, // 5 minutes
77
});
78
79
// Ensure data exists
80
const userData = await queryClient.ensureQueryData({
81
queryKey: ['user', 123],
82
queryFn: async () => {
83
const response = await fetch('/api/user/123');
84
return response.json();
85
},
86
revalidateIfStale: true,
87
});
88
```
89
90
### Query Lifecycle Management
91
92
Methods for managing query state and triggering updates.
93
94
```typescript { .api }
95
/**
96
* Invalidate queries matching the filters
97
* Marks queries as stale and triggers refetch for active queries
98
* @param filters - Query filters to match against
99
* @param options - Invalidation options
100
* @returns Promise that resolves when invalidation completes
101
*/
102
invalidateQueries(
103
filters?: InvalidateQueryFilters,
104
options?: InvalidateOptions
105
): Promise<void>;
106
107
/**
108
* Refetch queries matching the filters
109
* Forces immediate refetch regardless of staleness
110
* @param filters - Query filters to match against
111
* @param options - Refetch options
112
* @returns Promise that resolves when refetch completes
113
*/
114
refetchQueries(
115
filters?: RefetchQueryFilters,
116
options?: RefetchOptions
117
): Promise<void>;
118
119
/**
120
* Cancel ongoing queries matching the filters
121
* Aborts network requests and resets loading states
122
* @param filters - Query filters to match against
123
* @param options - Cancellation options
124
* @returns Promise that resolves when cancellation completes
125
*/
126
cancelQueries(filters?: QueryFilters, options?: CancelOptions): Promise<void>;
127
128
/**
129
* Remove queries from cache matching the filters
130
* Permanently removes queries and their cached data
131
* @param filters - Query filters to match against
132
*/
133
removeQueries(filters?: QueryFilters): void;
134
135
/**
136
* Reset queries to their initial state
137
* Clears data and error state, triggers refetch for active queries
138
* @param filters - Query filters to match against
139
* @param options - Reset options
140
* @returns Promise that resolves when reset completes
141
*/
142
resetQueries(filters?: QueryFilters, options?: ResetOptions): Promise<void>;
143
144
interface InvalidateQueryFilters extends QueryFilters {
145
refetchType?: 'active' | 'inactive' | 'all' | 'none';
146
}
147
148
interface RefetchQueryFilters extends QueryFilters {
149
type?: 'active' | 'inactive' | 'all';
150
}
151
152
interface InvalidateOptions {
153
refetchType?: 'active' | 'inactive' | 'all' | 'none';
154
}
155
156
interface RefetchOptions extends CancelOptions {
157
throwOnError?: boolean;
158
}
159
160
interface CancelOptions {
161
revert?: boolean;
162
silent?: boolean;
163
}
164
165
interface ResetOptions extends RefetchOptions {}
166
```
167
168
**Usage Examples:**
169
170
```typescript
171
// Invalidate all user queries
172
await queryClient.invalidateQueries({
173
queryKey: ['user'],
174
});
175
176
// Invalidate exact query
177
await queryClient.invalidateQueries({
178
queryKey: ['user', 123],
179
exact: true,
180
});
181
182
// Refetch only active queries
183
await queryClient.refetchQueries({
184
queryKey: ['posts'],
185
type: 'active',
186
});
187
188
// Cancel all ongoing fetches
189
await queryClient.cancelQueries();
190
191
// Remove stale queries
192
queryClient.removeQueries({
193
stale: true,
194
});
195
196
// Reset specific query
197
await queryClient.resetQueries({
198
queryKey: ['user', 123],
199
exact: true,
200
});
201
```
202
203
### Data Manipulation
204
205
Methods for directly manipulating cached query data.
206
207
```typescript { .api }
208
/**
209
* Get cached data for a specific query
210
* @param queryKey - The query key to retrieve data for
211
* @returns The cached data or undefined if not found
212
*/
213
getQueryData<T>(queryKey: QueryKey): T | undefined;
214
215
/**
216
* Set or update cached data for a specific query
217
* @param queryKey - The query key to set data for
218
* @param updater - New data or function to update existing data
219
* @param options - Additional options for setting data
220
* @returns The updated data
221
*/
222
setQueryData<T>(
223
queryKey: QueryKey,
224
updater: Updater<T>,
225
options?: SetDataOptions
226
): T | undefined;
227
228
/**
229
* Get cached data for multiple queries matching filters
230
* @param filters - Query filters to match against
231
* @returns Array of [queryKey, data] tuples
232
*/
233
getQueriesData<T>(filters: QueryFilters): Array<[QueryKey, T | undefined]>;
234
235
/**
236
* Set cached data for multiple queries matching filters
237
* @param filters - Query filters to match against
238
* @param updater - New data or function to update existing data
239
* @param options - Additional options for setting data
240
* @returns Array of [queryKey, data] tuples
241
*/
242
setQueriesData<T>(
243
filters: QueryFilters,
244
updater: Updater<T>,
245
options?: SetDataOptions
246
): Array<[QueryKey, T | undefined]>;
247
248
interface SetDataOptions {
249
updatedAt?: number;
250
}
251
```
252
253
**Usage Examples:**
254
255
```typescript
256
// Get cached data
257
const userData = queryClient.getQueryData(['user', 123]);
258
259
// Set data with new value
260
queryClient.setQueryData(['user', 123], {
261
id: 123,
262
name: 'John Doe',
263
email: 'john@example.com',
264
});
265
266
// Update data functionally
267
queryClient.setQueryData(['user', 123], (oldData) => ({
268
...oldData,
269
lastSeen: new Date().toISOString(),
270
}));
271
272
// Get data from multiple queries
273
const allUserData = queryClient.getQueriesData({
274
queryKey: ['user'],
275
});
276
277
// Update multiple queries
278
queryClient.setQueriesData(
279
{ queryKey: ['user'] },
280
(oldData) => ({ ...oldData, updated: true })
281
);
282
```
283
284
### Query State Access
285
286
Methods for accessing detailed query state information.
287
288
```typescript { .api }
289
/**
290
* Get the complete state for a specific query
291
* @param queryKey - The query key to get state for
292
* @returns The query state or undefined if not found
293
*/
294
getQueryState<T>(queryKey: QueryKey): QueryState<T> | undefined;
295
296
interface QueryState<TData = unknown, TError = Error> {
297
data: TData | undefined;
298
dataUpdateCount: number;
299
dataUpdatedAt: number;
300
error: TError | null;
301
errorUpdateCount: number;
302
errorUpdatedAt: number;
303
fetchFailureCount: number;
304
fetchFailureReason: TError | null;
305
fetchMeta: FetchMeta | null;
306
isInvalidated: boolean;
307
status: QueryStatus;
308
fetchStatus: FetchStatus;
309
}
310
```
311
312
**Usage Examples:**
313
314
```typescript
315
// Get complete query state
316
const queryState = queryClient.getQueryState(['user', 123]);
317
318
if (queryState) {
319
console.log('Data:', queryState.data);
320
console.log('Status:', queryState.status);
321
console.log('Last updated:', new Date(queryState.dataUpdatedAt));
322
console.log('Error count:', queryState.fetchFailureCount);
323
console.log('Is invalidated:', queryState.isInvalidated);
324
}
325
```
326
327
## Query Filters
328
329
```typescript { .api }
330
interface QueryFilters {
331
/**
332
* Query key to match against
333
* Can be exact match or partial match depending on 'exact' option
334
*/
335
queryKey?: QueryKey;
336
337
/**
338
* Whether to match the query key exactly
339
* If false, performs partial matching
340
*/
341
exact?: boolean;
342
343
/**
344
* Filter by stale status
345
* true: only stale queries, false: only fresh queries
346
*/
347
stale?: boolean;
348
349
/**
350
* Filter by active status (has active observers)
351
* true: only active queries, false: only inactive queries
352
*/
353
active?: boolean;
354
355
/**
356
* Filter by inactive status (no active observers)
357
* true: only inactive queries, false: only active queries
358
*/
359
inactive?: boolean;
360
361
/**
362
* Custom predicate function for advanced filtering
363
* @param query - The query to test
364
* @returns true if query matches filter
365
*/
366
predicate?: (query: Query) => boolean;
367
368
/**
369
* Filter by fetch status
370
*/
371
fetchStatus?: FetchStatus;
372
373
/**
374
* Filter by query type
375
*/
376
type?: QueryTypeFilter;
377
}
378
379
type QueryTypeFilter = 'all' | 'active' | 'inactive';
380
```
381
382
## Core Types
383
384
```typescript { .api }
385
type QueryKey = ReadonlyArray<unknown>;
386
387
type QueryFunction<T = unknown, TQueryKey extends QueryKey = QueryKey> = (
388
context: QueryFunctionContext<TQueryKey>
389
) => T | Promise<T>;
390
391
interface QueryFunctionContext<TQueryKey extends QueryKey = QueryKey> {
392
queryKey: TQueryKey;
393
signal: AbortSignal;
394
meta: QueryMeta | undefined;
395
pageParam?: unknown;
396
direction?: 'forward' | 'backward';
397
}
398
399
type QueryStatus = 'pending' | 'error' | 'success';
400
type FetchStatus = 'fetching' | 'paused' | 'idle';
401
type NetworkMode = 'online' | 'always' | 'offlineFirst';
402
403
type RetryValue<TError> = boolean | number | ((failureCount: number, error: TError) => boolean);
404
405
type InitialDataFunction<T> = () => T | undefined;
406
407
interface QueryMeta extends Record<string, unknown> {}
408
interface FetchMeta extends Record<string, unknown> {}
409
410
type Updater<T> = T | ((old: T) => T);
411
```