@punks/cli 2.1.9 → 2.1.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/data/catalog/hooks.ts +8 -0
- package/dist/data/catalog/packs.ts +11 -3
- package/dist/data/catalog/skills.ts +48 -0
- package/dist/data/catalog/tools.ts +9 -1
- package/dist/data/hooks/scaffold-update-check.mjs +181 -0
- package/dist/data/hooks.test.ts +17 -0
- package/dist/data/scripts/sync-subagents.mjs +104 -32
- package/dist/data/subagents/manifest.mjs +120 -0
- package/dist/index.js +600 -85
- package/dist/skills/agnostic/cli/dp-cli/SKILL.md +3 -3
- package/dist/skills/agnostic/cli/dp-cli/references/commands.md +1 -1
- package/dist/skills/agnostic/cli/dp-cli/references/post-command-flow.md +1 -1
- package/dist/skills/agnostic/docs/docs-onboarding/SKILL.md +46 -0
- package/dist/skills/agnostic/docs/docs-onboarding/agents/openai.yaml +4 -0
- package/dist/skills/agnostic/docs/docs-onboarding/references/artifact-contract.md +67 -0
- package/dist/skills/agnostic/docs/writing-beats/SKILL.md +69 -0
- package/dist/skills/agnostic/docs/writing-fragments/SKILL.md +76 -0
- package/dist/skills/agnostic/docs/writing-shape/SKILL.md +75 -0
- package/dist/skills/agnostic/generic/handoff/SKILL.md +15 -0
- package/dist/skills/agnostic/planning/create-plan/SKILL.md +24 -8
- package/dist/skills/agnostic/planning/create-plan/references/plan-schema.md +20 -0
- package/dist/skills/agnostic/planning/create-plan/references/planner-phase.md +1 -1
- package/dist/skills/agnostic/planning/create-plan/references/tdd-phase.md +23 -1
- package/dist/skills/agnostic/planning/create-spec/SKILL.md +63 -17
- package/dist/skills/agnostic/planning/create-spec/references/discovery.md +24 -16
- package/dist/skills/agnostic/planning/create-spec/references/folder-naming.md +6 -2
- package/dist/skills/agnostic/planning/create-spec/references/wiki-bookkeeping.md +29 -5
- package/dist/skills/agnostic/planning/implement-spec/SKILL.md +20 -2
- package/dist/skills/agnostic/planning/implement-spec/references/lifecycle.md +7 -1
- package/dist/skills/agnostic/planning/implement-spec/references/parallel-worker-brief.md +15 -8
- package/dist/skills/agnostic/planning/implement-spec/references/sequential.md +8 -3
- package/dist/skills/agnostic/planning/stack/SKILL.md +89 -0
- package/dist/skills/agnostic/quality/tdd/SKILL.md +31 -0
- package/dist/skills/agnostic/requirements/requirements-grill/SKILL.md +1 -0
- package/dist/skills/agnostic/requirements/write-backlog/SKILL.md +7 -5
- package/dist/skills/frameworks/tanstack-query/tanstack-query/SKILL.md +621 -830
- package/dist/skills/frameworks/tanstack-start/tanstack-start/SKILL.md +250 -0
- package/dist/skills/phases/bug-discovery-phase/REFERENCE.md +30 -0
- package/dist/skills/phases/bug-discovery-phase/SKILL.md +8 -1
- package/dist/skills/phases/debugging-phase/SKILL.md +1 -0
- package/dist/skills/phases/delivery-phase/SKILL.md +33 -65
- package/dist/skills/phases/delivery-phase/phases/closeout.md +33 -0
- package/dist/skills/phases/delivery-phase/phases/debug.md +30 -0
- package/dist/skills/phases/delivery-phase/phases/docs-ingest.md +27 -0
- package/dist/skills/phases/delivery-phase/phases/implement.md +30 -0
- package/dist/skills/phases/delivery-phase/phases/plan.md +27 -0
- package/dist/skills/phases/delivery-phase/phases/review.md +29 -0
- package/dist/skills/phases/delivery-phase/phases/router.md +46 -0
- package/dist/skills/phases/delivery-phase/phases/spec.md +26 -0
- package/dist/skills/phases/delivery-phase/references/artifact-state.md +42 -0
- package/dist/skills/phases/delivery-phase/references/phase-handoff.md +25 -0
- package/dist/skills/phases/docs-ingest-phase/SKILL.md +28 -70
- package/dist/skills/phases/docs-ingest-phase/agents/openai.yaml +2 -2
- package/dist/skills/phases/docs-ingest-phase/phases/private-internal.md +57 -0
- package/dist/skills/phases/docs-ingest-phase/phases/public-docs.md +52 -0
- package/dist/skills/phases/docs-ingest-phase/phases/router.md +42 -0
- package/dist/skills/phases/docs-ingest-phase/references/fumadocs-routing.md +8 -5
- package/dist/skills/phases/docs-ingest-phase/references/learning-artifacts.md +96 -0
- package/dist/skills/phases/docs-ingest-phase/references/public-docs.md +90 -0
- package/dist/skills/phases/requirements-phase/SKILL.md +3 -0
- package/dist/skills/phases/review-phase/SKILL.md +5 -0
- package/package.json +1 -1
|
@@ -1,1058 +1,849 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: tanstack-query
|
|
3
|
-
description:
|
|
4
|
-
Manage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions.
|
|
5
|
-
|
|
6
|
-
Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
|
|
7
|
-
user-invocable: true
|
|
8
|
-
---
|
|
9
|
-
|
|
10
|
-
# TanStack Query (React Query) v5
|
|
11
|
-
|
|
12
|
-
**Last Updated**: 2026-01-20
|
|
13
|
-
**Versions**: @tanstack/react-query@5.90.19, @tanstack/react-query-devtools@5.91.2
|
|
14
|
-
**Requires**: React 18.0+ (useSyncExternalStore), TypeScript 4.7+ (recommended)
|
|
15
|
-
|
|
3
|
+
description: Powerful asynchronous state management, server-state utilities, and data fetching for TS/JS, React, Vue, Solid, Svelte & Angular.
|
|
16
4
|
---
|
|
17
5
|
|
|
18
|
-
## v5 New Features
|
|
19
|
-
|
|
20
|
-
### useMutationState - Cross-Component Mutation Tracking
|
|
21
6
|
|
|
22
|
-
|
|
7
|
+
## Overview
|
|
23
8
|
|
|
24
|
-
|
|
25
|
-
import { useMutationState } from '@tanstack/react-query'
|
|
9
|
+
TanStack Query (formerly React Query) manages server state - data that lives on the server and needs to be fetched, cached, synchronized, and updated. It provides automatic caching, background refetching, stale-while-revalidate patterns, pagination, infinite scrolling, and optimistic updates out of the box.
|
|
26
10
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
filters: { status: 'pending' },
|
|
31
|
-
select: (mutation) => mutation.state.variables,
|
|
32
|
-
})
|
|
11
|
+
**Package:** `@tanstack/react-query`
|
|
12
|
+
**Devtools:** `@tanstack/react-query-devtools`
|
|
13
|
+
**Current Version:** v5
|
|
33
14
|
|
|
34
|
-
|
|
35
|
-
return <div>Saving {pendingMutations.length} items...</div>
|
|
36
|
-
}
|
|
15
|
+
## Installation
|
|
37
16
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
})
|
|
17
|
+
```bash
|
|
18
|
+
npm install @tanstack/react-query
|
|
19
|
+
npm install -D @tanstack/react-query-devtools # Optional
|
|
42
20
|
```
|
|
43
21
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
New pattern using `variables` - no cache manipulation, no rollback needed:
|
|
22
|
+
## Setup
|
|
47
23
|
|
|
48
24
|
```tsx
|
|
49
|
-
|
|
50
|
-
|
|
25
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
26
|
+
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
|
|
51
27
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
28
|
+
const queryClient = new QueryClient({
|
|
29
|
+
defaultOptions: {
|
|
30
|
+
queries: {
|
|
31
|
+
staleTime: 1000 * 60, // 1 minute
|
|
32
|
+
gcTime: 1000 * 60 * 5, // 5 minutes (garbage collection)
|
|
33
|
+
retry: 3,
|
|
34
|
+
refetchOnWindowFocus: true,
|
|
35
|
+
refetchOnReconnect: true,
|
|
57
36
|
},
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// Show optimistic UI using variables from pending mutations
|
|
61
|
-
const pendingTodos = useMutationState({
|
|
62
|
-
filters: { mutationKey: ['addTodo'], status: 'pending' },
|
|
63
|
-
select: (mutation) => mutation.state.variables,
|
|
64
|
-
})
|
|
37
|
+
},
|
|
38
|
+
})
|
|
65
39
|
|
|
40
|
+
function App() {
|
|
66
41
|
return (
|
|
67
|
-
<
|
|
68
|
-
|
|
69
|
-
{
|
|
70
|
-
|
|
71
|
-
<li key={`pending-${i}`} style={{ opacity: 0.5 }}>{todo.title}</li>
|
|
72
|
-
))}
|
|
73
|
-
</ul>
|
|
42
|
+
<QueryClientProvider client={queryClient}>
|
|
43
|
+
<YourApp />
|
|
44
|
+
<ReactQueryDevtools initialIsOpen={false} />
|
|
45
|
+
</QueryClientProvider>
|
|
74
46
|
)
|
|
75
47
|
}
|
|
76
48
|
```
|
|
77
49
|
|
|
78
|
-
|
|
50
|
+
## Core Concepts
|
|
51
|
+
|
|
52
|
+
### Query Keys
|
|
79
53
|
|
|
80
|
-
|
|
54
|
+
Query keys uniquely identify cached data. They must be serializable arrays:
|
|
81
55
|
|
|
82
56
|
```tsx
|
|
83
|
-
|
|
84
|
-
|
|
57
|
+
// Simple key
|
|
58
|
+
useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
|
|
85
59
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
<QueryErrorResetBoundary>
|
|
89
|
-
{({ reset }) => (
|
|
90
|
-
<ErrorBoundary onReset={reset} fallbackRender={({ resetErrorBoundary }) => (
|
|
91
|
-
<div>
|
|
92
|
-
Error! <button onClick={resetErrorBoundary}>Retry</button>
|
|
93
|
-
</div>
|
|
94
|
-
)}>
|
|
95
|
-
<Todos />
|
|
96
|
-
</ErrorBoundary>
|
|
97
|
-
)}
|
|
98
|
-
</QueryErrorResetBoundary>
|
|
99
|
-
)
|
|
100
|
-
}
|
|
60
|
+
// With variables (dependency array pattern)
|
|
61
|
+
useQuery({ queryKey: ['todos', { status, page }], queryFn: fetchTodos })
|
|
101
62
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
queryFn: fetchTodos,
|
|
106
|
-
throwOnError: true, // ✅ v5 (was useErrorBoundary in v4)
|
|
107
|
-
})
|
|
108
|
-
return <div>{data.map(...)}</div>
|
|
109
|
-
}
|
|
110
|
-
```
|
|
63
|
+
// Hierarchical keys for invalidation
|
|
64
|
+
useQuery({ queryKey: ['todos', todoId], queryFn: () => fetchTodo(todoId) })
|
|
65
|
+
useQuery({ queryKey: ['todos', todoId, 'comments'], queryFn: () => fetchComments(todoId) })
|
|
111
66
|
|
|
112
|
-
|
|
67
|
+
// Invalidation matches prefixes:
|
|
68
|
+
// queryClient.invalidateQueries({ queryKey: ['todos'] })
|
|
69
|
+
// ^ Invalidates ALL queries starting with 'todos'
|
|
70
|
+
```
|
|
113
71
|
|
|
114
|
-
|
|
72
|
+
### Query Functions
|
|
115
73
|
|
|
116
74
|
```tsx
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
75
|
+
// Query function receives a QueryFunctionContext
|
|
76
|
+
useQuery({
|
|
77
|
+
queryKey: ['todos', todoId],
|
|
78
|
+
queryFn: async ({ queryKey, signal, meta }) => {
|
|
79
|
+
const [_key, id] = queryKey
|
|
80
|
+
const response = await fetch(`/api/todos/${id}`, { signal })
|
|
81
|
+
if (!response.ok) throw new Error('Failed to fetch')
|
|
82
|
+
return response.json()
|
|
122
83
|
},
|
|
123
84
|
})
|
|
124
85
|
|
|
125
|
-
//
|
|
86
|
+
// Using the signal for automatic cancellation
|
|
126
87
|
useQuery({
|
|
127
88
|
queryKey: ['todos'],
|
|
128
|
-
queryFn:
|
|
129
|
-
|
|
89
|
+
queryFn: async ({ signal }) => {
|
|
90
|
+
const response = await fetch('/api/todos', { signal })
|
|
91
|
+
return response.json()
|
|
92
|
+
},
|
|
130
93
|
})
|
|
131
94
|
```
|
|
132
95
|
|
|
133
|
-
|
|
134
|
-
|------|----------|
|
|
135
|
-
| `online` (default) | Only fetch when online |
|
|
136
|
-
| `always` | Always try (useful for local/service worker APIs) |
|
|
137
|
-
| `offlineFirst` | Use cache first, fetch when online |
|
|
138
|
-
|
|
139
|
-
**Detecting paused state:**
|
|
140
|
-
```tsx
|
|
141
|
-
const { isPending, fetchStatus } = useQuery(...)
|
|
142
|
-
// isPending + fetchStatus === 'paused' = offline, waiting for network
|
|
143
|
-
```
|
|
144
|
-
|
|
145
|
-
### useQueries with Combine
|
|
96
|
+
### queryOptions Helper
|
|
146
97
|
|
|
147
|
-
|
|
98
|
+
Create reusable, type-safe query configurations:
|
|
148
99
|
|
|
149
100
|
```tsx
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
data: results.map(r => r.data),
|
|
157
|
-
pending: results.some(r => r.isPending),
|
|
158
|
-
error: results.find(r => r.error)?.error,
|
|
159
|
-
}),
|
|
101
|
+
import { queryOptions } from '@tanstack/react-query'
|
|
102
|
+
|
|
103
|
+
export const todosQueryOptions = queryOptions({
|
|
104
|
+
queryKey: ['todos'],
|
|
105
|
+
queryFn: fetchTodos,
|
|
106
|
+
staleTime: 5000,
|
|
160
107
|
})
|
|
161
108
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
109
|
+
export const todoQueryOptions = (todoId: string) =>
|
|
110
|
+
queryOptions({
|
|
111
|
+
queryKey: ['todos', todoId],
|
|
112
|
+
queryFn: () => fetchTodo(todoId),
|
|
113
|
+
enabled: !!todoId,
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
// Usage
|
|
117
|
+
const { data } = useQuery(todosQueryOptions)
|
|
118
|
+
const { data } = useSuspenseQuery(todoQueryOptions(id))
|
|
119
|
+
await queryClient.prefetchQuery(todosQueryOptions)
|
|
165
120
|
```
|
|
166
121
|
|
|
167
|
-
|
|
122
|
+
## Queries (useQuery)
|
|
168
123
|
|
|
169
|
-
|
|
124
|
+
### Basic Usage
|
|
170
125
|
|
|
171
126
|
```tsx
|
|
172
|
-
import {
|
|
127
|
+
import { useQuery } from '@tanstack/react-query'
|
|
173
128
|
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
129
|
+
function Todos() {
|
|
130
|
+
const {
|
|
131
|
+
data,
|
|
132
|
+
error,
|
|
133
|
+
isLoading, // First load, no data yet
|
|
134
|
+
isFetching, // Any fetch in progress (including background)
|
|
135
|
+
isError,
|
|
136
|
+
isSuccess,
|
|
137
|
+
isPending, // No data yet (same as isLoading in most cases)
|
|
138
|
+
status, // 'pending' | 'error' | 'success'
|
|
139
|
+
fetchStatus, // 'fetching' | 'paused' | 'idle'
|
|
140
|
+
refetch,
|
|
141
|
+
isStale,
|
|
142
|
+
isPlaceholderData,
|
|
143
|
+
dataUpdatedAt,
|
|
144
|
+
errorUpdatedAt,
|
|
145
|
+
} = useQuery({
|
|
146
|
+
queryKey: ['todos'],
|
|
147
|
+
queryFn: fetchTodos,
|
|
148
|
+
})
|
|
180
149
|
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
150
|
+
if (isLoading) return <Spinner />
|
|
151
|
+
if (isError) return <Error message={error.message} />
|
|
152
|
+
return <TodoList todos={data} />
|
|
153
|
+
}
|
|
185
154
|
```
|
|
186
155
|
|
|
187
|
-
###
|
|
188
|
-
|
|
189
|
-
Limit pages stored in cache for infinite queries:
|
|
156
|
+
### Query Options
|
|
190
157
|
|
|
191
158
|
```tsx
|
|
192
|
-
|
|
193
|
-
queryKey: ['
|
|
194
|
-
queryFn:
|
|
195
|
-
initialPageParam: 0,
|
|
196
|
-
getNextPageParam: (lastPage) => lastPage.nextCursor,
|
|
197
|
-
getPreviousPageParam: (firstPage) => firstPage.prevCursor, // Required with maxPages
|
|
198
|
-
maxPages: 3, // Only keep 3 pages in memory
|
|
199
|
-
})
|
|
200
|
-
```
|
|
159
|
+
useQuery({
|
|
160
|
+
queryKey: ['todos'],
|
|
161
|
+
queryFn: fetchTodos,
|
|
201
162
|
|
|
202
|
-
|
|
163
|
+
// Freshness
|
|
164
|
+
staleTime: 5000, // ms data stays fresh (default: 0)
|
|
165
|
+
gcTime: 300000, // ms unused data stays in cache (default: 5 min)
|
|
203
166
|
|
|
204
|
-
|
|
167
|
+
// Refetching
|
|
168
|
+
refetchInterval: 10000, // Poll every 10s
|
|
169
|
+
refetchIntervalInBackground: false, // Don't poll when tab hidden
|
|
170
|
+
refetchOnMount: true, // Refetch on component mount if stale
|
|
171
|
+
refetchOnWindowFocus: true, // Refetch on window focus if stale
|
|
172
|
+
refetchOnReconnect: true, // Refetch on network reconnect
|
|
205
173
|
|
|
206
|
-
|
|
174
|
+
// Retry
|
|
175
|
+
retry: 3, // Number of retries (or function)
|
|
176
|
+
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
|
|
207
177
|
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
npm install -D @tanstack/react-query-devtools@latest
|
|
211
|
-
```
|
|
178
|
+
// Conditional
|
|
179
|
+
enabled: !!userId, // Only run when truthy
|
|
212
180
|
|
|
213
|
-
|
|
181
|
+
// Initial/placeholder data
|
|
182
|
+
initialData: () => cachedData,
|
|
183
|
+
initialDataUpdatedAt: Date.now() - 10000,
|
|
184
|
+
placeholderData: (previousData) => previousData, // keepPreviousData pattern
|
|
185
|
+
placeholderData: initialTodos,
|
|
214
186
|
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
218
|
-
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
|
|
187
|
+
// Transform
|
|
188
|
+
select: (data) => data.filter(todo => !todo.done),
|
|
219
189
|
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
queries: {
|
|
223
|
-
staleTime: 1000 * 60 * 5, // 5 min
|
|
224
|
-
gcTime: 1000 * 60 * 60, // 1 hour (v5: renamed from cacheTime)
|
|
225
|
-
refetchOnWindowFocus: false,
|
|
226
|
-
},
|
|
227
|
-
},
|
|
228
|
-
})
|
|
190
|
+
// Structural sharing (default: true)
|
|
191
|
+
structuralSharing: true,
|
|
229
192
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
<ReactQueryDevtools initialIsOpen={false} />
|
|
233
|
-
</QueryClientProvider>
|
|
234
|
-
```
|
|
193
|
+
// Network mode
|
|
194
|
+
networkMode: 'online', // 'online' | 'always' | 'offlineFirst'
|
|
235
195
|
|
|
236
|
-
|
|
196
|
+
// Meta (accessible in query function context)
|
|
197
|
+
meta: { purpose: 'user-facing' },
|
|
198
|
+
})
|
|
199
|
+
```
|
|
237
200
|
|
|
238
|
-
|
|
239
|
-
// src/hooks/useTodos.ts
|
|
240
|
-
import { useQuery, useMutation, useQueryClient, queryOptions } from '@tanstack/react-query'
|
|
201
|
+
## Mutations (useMutation)
|
|
241
202
|
|
|
242
|
-
|
|
243
|
-
export const todosQueryOptions = queryOptions({
|
|
244
|
-
queryKey: ['todos'],
|
|
245
|
-
queryFn: async () => {
|
|
246
|
-
const res = await fetch('/api/todos')
|
|
247
|
-
if (!res.ok) throw new Error('Failed to fetch')
|
|
248
|
-
return res.json()
|
|
249
|
-
},
|
|
250
|
-
})
|
|
203
|
+
### Basic Usage
|
|
251
204
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
}
|
|
205
|
+
```tsx
|
|
206
|
+
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
|
255
207
|
|
|
256
|
-
|
|
208
|
+
function AddTodo() {
|
|
257
209
|
const queryClient = useQueryClient()
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
210
|
+
|
|
211
|
+
const mutation = useMutation({
|
|
212
|
+
mutationFn: (newTodo: { title: string }) => {
|
|
213
|
+
return fetch('/api/todos', {
|
|
261
214
|
method: 'POST',
|
|
262
|
-
headers: { 'Content-Type': 'application/json' },
|
|
263
215
|
body: JSON.stringify(newTodo),
|
|
264
|
-
})
|
|
265
|
-
|
|
266
|
-
|
|
216
|
+
}).then(res => res.json())
|
|
217
|
+
},
|
|
218
|
+
// Lifecycle callbacks
|
|
219
|
+
onMutate: async (variables) => {
|
|
220
|
+
// Called before mutationFn
|
|
221
|
+
// Good for optimistic updates
|
|
222
|
+
return { previousTodos } // context for onError
|
|
267
223
|
},
|
|
268
|
-
onSuccess: () => {
|
|
224
|
+
onSuccess: (data, variables, context) => {
|
|
225
|
+
// Invalidate related queries
|
|
226
|
+
queryClient.invalidateQueries({ queryKey: ['todos'] })
|
|
227
|
+
},
|
|
228
|
+
onError: (error, variables, context) => {
|
|
229
|
+
// Rollback optimistic updates
|
|
230
|
+
queryClient.setQueryData(['todos'], context.previousTodos)
|
|
231
|
+
},
|
|
232
|
+
onSettled: (data, error, variables, context) => {
|
|
233
|
+
// Always runs (success or error)
|
|
269
234
|
queryClient.invalidateQueries({ queryKey: ['todos'] })
|
|
270
235
|
},
|
|
271
236
|
})
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
// Usage:
|
|
275
|
-
function TodoList() {
|
|
276
|
-
const { data, isPending, isError, error } = useTodos()
|
|
277
|
-
const { mutate } = useAddTodo()
|
|
278
237
|
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
238
|
+
return (
|
|
239
|
+
<button
|
|
240
|
+
onClick={() => mutation.mutate({ title: 'New Todo' })}
|
|
241
|
+
disabled={mutation.isPending}
|
|
242
|
+
>
|
|
243
|
+
{mutation.isPending ? 'Adding...' : 'Add Todo'}
|
|
244
|
+
</button>
|
|
245
|
+
)
|
|
282
246
|
}
|
|
283
247
|
```
|
|
284
248
|
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
## Critical Rules
|
|
288
|
-
|
|
289
|
-
### Always Do
|
|
290
|
-
|
|
291
|
-
✅ **Use object syntax for all hooks**
|
|
292
|
-
```tsx
|
|
293
|
-
// v5 ONLY supports this:
|
|
294
|
-
useQuery({ queryKey, queryFn, ...options })
|
|
295
|
-
useMutation({ mutationFn, ...options })
|
|
296
|
-
```
|
|
297
|
-
|
|
298
|
-
✅ **Use array query keys**
|
|
299
|
-
```tsx
|
|
300
|
-
queryKey: ['todos'] // List
|
|
301
|
-
queryKey: ['todos', id] // Detail
|
|
302
|
-
queryKey: ['todos', { filter }] // Filtered
|
|
303
|
-
```
|
|
249
|
+
### Mutation State
|
|
304
250
|
|
|
305
|
-
✅ **Configure staleTime appropriately**
|
|
306
251
|
```tsx
|
|
307
|
-
|
|
252
|
+
const {
|
|
253
|
+
mutate, // Fire-and-forget
|
|
254
|
+
mutateAsync, // Returns promise
|
|
255
|
+
isPending, // Mutation in progress
|
|
256
|
+
isError,
|
|
257
|
+
isSuccess,
|
|
258
|
+
isIdle, // Not yet fired
|
|
259
|
+
data, // Success response
|
|
260
|
+
error, // Error object
|
|
261
|
+
reset, // Reset state to idle
|
|
262
|
+
variables, // Variables passed to mutate
|
|
263
|
+
status, // 'idle' | 'pending' | 'error' | 'success'
|
|
264
|
+
} = useMutation({ ... })
|
|
308
265
|
```
|
|
309
266
|
|
|
310
|
-
|
|
311
|
-
```tsx
|
|
312
|
-
if (isPending) return <Loading />
|
|
313
|
-
// isPending = no data yet AND fetching
|
|
314
|
-
```
|
|
267
|
+
## Optimistic Updates
|
|
315
268
|
|
|
316
|
-
✅ **Throw errors in queryFn**
|
|
317
269
|
```tsx
|
|
318
|
-
|
|
319
|
-
|
|
270
|
+
const mutation = useMutation({
|
|
271
|
+
mutationFn: updateTodo,
|
|
272
|
+
onMutate: async (newTodo) => {
|
|
273
|
+
// 1. Cancel outgoing refetches
|
|
274
|
+
await queryClient.cancelQueries({ queryKey: ['todos', newTodo.id] })
|
|
320
275
|
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
onSuccess: () => {
|
|
324
|
-
queryClient.invalidateQueries({ queryKey: ['todos'] })
|
|
325
|
-
}
|
|
326
|
-
```
|
|
276
|
+
// 2. Snapshot previous value
|
|
277
|
+
const previousTodo = queryClient.getQueryData(['todos', newTodo.id])
|
|
327
278
|
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
const opts = queryOptions({ queryKey, queryFn })
|
|
331
|
-
useQuery(opts)
|
|
332
|
-
useSuspenseQuery(opts)
|
|
333
|
-
prefetchQuery(opts)
|
|
334
|
-
```
|
|
279
|
+
// 3. Optimistically update
|
|
280
|
+
queryClient.setQueryData(['todos', newTodo.id], newTodo)
|
|
335
281
|
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
282
|
+
// 4. Return context for rollback
|
|
283
|
+
return { previousTodo }
|
|
284
|
+
},
|
|
285
|
+
onError: (err, newTodo, context) => {
|
|
286
|
+
// Rollback on error
|
|
287
|
+
queryClient.setQueryData(['todos', newTodo.id], context.previousTodo)
|
|
288
|
+
},
|
|
289
|
+
onSettled: () => {
|
|
290
|
+
// Always refetch to sync with server
|
|
291
|
+
queryClient.invalidateQueries({ queryKey: ['todos'] })
|
|
292
|
+
},
|
|
293
|
+
})
|
|
339
294
|
```
|
|
340
295
|
|
|
341
|
-
###
|
|
342
|
-
|
|
343
|
-
❌ **Never use v4 array/function syntax**
|
|
344
|
-
```tsx
|
|
345
|
-
// v4 (removed in v5):
|
|
346
|
-
useQuery(['todos'], fetchTodos, options) // ❌
|
|
347
|
-
|
|
348
|
-
// v5 (correct):
|
|
349
|
-
useQuery({ queryKey: ['todos'], queryFn: fetchTodos }) // ✅
|
|
350
|
-
```
|
|
296
|
+
### Optimistic Updates on Lists
|
|
351
297
|
|
|
352
|
-
❌ **Never use query callbacks (onSuccess, onError, onSettled in queries)**
|
|
353
298
|
```tsx
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
queryFn: fetchTodos,
|
|
358
|
-
onSuccess: (data) => {}, // ❌ Removed in v5
|
|
359
|
-
})
|
|
299
|
+
onMutate: async (newTodo) => {
|
|
300
|
+
await queryClient.cancelQueries({ queryKey: ['todos'] })
|
|
301
|
+
const previousTodos = queryClient.getQueryData(['todos'])
|
|
360
302
|
|
|
361
|
-
|
|
362
|
-
const { data } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
|
|
363
|
-
useEffect(() => {
|
|
364
|
-
if (data) {
|
|
365
|
-
// Do something
|
|
366
|
-
}
|
|
367
|
-
}, [data])
|
|
368
|
-
|
|
369
|
-
// Or use mutation callbacks (still supported):
|
|
370
|
-
useMutation({
|
|
371
|
-
mutationFn: addTodo,
|
|
372
|
-
onSuccess: () => {}, // ✅ Still works for mutations
|
|
373
|
-
})
|
|
374
|
-
```
|
|
303
|
+
queryClient.setQueryData(['todos'], (old) => [...old, newTodo])
|
|
375
304
|
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
keepPreviousData: true // ❌ Use placeholderData instead
|
|
382
|
-
onSuccess: () => {} // ❌ Removed from queries
|
|
383
|
-
useErrorBoundary: true // ❌ Use throwOnError instead
|
|
305
|
+
return { previousTodos }
|
|
306
|
+
},
|
|
307
|
+
onError: (err, newTodo, context) => {
|
|
308
|
+
queryClient.setQueryData(['todos'], context.previousTodos)
|
|
309
|
+
},
|
|
384
310
|
```
|
|
385
311
|
|
|
386
|
-
|
|
387
|
-
```tsx
|
|
388
|
-
// v5 changed this:
|
|
389
|
-
isLoading = isPending && isFetching // ❌ Now means "pending AND fetching"
|
|
390
|
-
isPending = no data yet // ✅ Use this for initial load
|
|
391
|
-
```
|
|
312
|
+
## Query Invalidation
|
|
392
313
|
|
|
393
|
-
❌ **Never forget initialPageParam for infinite queries**
|
|
394
314
|
```tsx
|
|
395
|
-
|
|
396
|
-
useInfiniteQuery({
|
|
397
|
-
queryKey: ['projects'],
|
|
398
|
-
queryFn: ({ pageParam }) => fetchProjects(pageParam),
|
|
399
|
-
initialPageParam: 0, // ✅ Required in v5
|
|
400
|
-
getNextPageParam: (lastPage) => lastPage.nextCursor,
|
|
401
|
-
})
|
|
402
|
-
```
|
|
315
|
+
const queryClient = useQueryClient()
|
|
403
316
|
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
// Not allowed:
|
|
407
|
-
useSuspenseQuery({
|
|
408
|
-
queryKey: ['todo', id],
|
|
409
|
-
queryFn: () => fetchTodo(id),
|
|
410
|
-
enabled: !!id, // ❌ Not available with suspense
|
|
411
|
-
})
|
|
317
|
+
// Invalidate all queries
|
|
318
|
+
queryClient.invalidateQueries()
|
|
412
319
|
|
|
413
|
-
//
|
|
414
|
-
{
|
|
415
|
-
```
|
|
320
|
+
// Invalidate by prefix
|
|
321
|
+
queryClient.invalidateQueries({ queryKey: ['todos'] })
|
|
416
322
|
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
// Doesn't work - errors are always stale
|
|
420
|
-
useQuery({
|
|
421
|
-
queryKey: ['data'],
|
|
422
|
-
queryFn: failingFetch,
|
|
423
|
-
refetchOnMount: false, // ❌ Ignored when query has error
|
|
424
|
-
})
|
|
323
|
+
// Invalidate exact match
|
|
324
|
+
queryClient.invalidateQueries({ queryKey: ['todos', 1], exact: true })
|
|
425
325
|
|
|
426
|
-
//
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
refetchOnMount: false,
|
|
431
|
-
retryOnMount: false, // ✅ Prevents refetch for errored queries
|
|
432
|
-
retry: 0,
|
|
326
|
+
// Invalidate with predicate
|
|
327
|
+
queryClient.invalidateQueries({
|
|
328
|
+
predicate: (query) =>
|
|
329
|
+
query.queryKey[0] === 'todos' && query.queryKey[1]?.status === 'done',
|
|
433
330
|
})
|
|
434
|
-
```
|
|
435
331
|
|
|
436
|
-
|
|
332
|
+
// Invalidate and refetch immediately
|
|
333
|
+
queryClient.refetchQueries({ queryKey: ['todos'] })
|
|
437
334
|
|
|
438
|
-
|
|
335
|
+
// Remove from cache entirely
|
|
336
|
+
queryClient.removeQueries({ queryKey: ['todos', 1] })
|
|
439
337
|
|
|
440
|
-
|
|
338
|
+
// Reset to initial state
|
|
339
|
+
queryClient.resetQueries({ queryKey: ['todos'] })
|
|
340
|
+
```
|
|
441
341
|
|
|
442
|
-
|
|
443
|
-
**Error**: `useQuery is not a function` or type errors
|
|
444
|
-
**Source**: [v5 Migration Guide](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#removed-overloads-in-favor-of-object-syntax)
|
|
445
|
-
**Why It Happens**: v5 removed all function overloads, only object syntax works
|
|
446
|
-
**Prevention**: Always use `useQuery({ queryKey, queryFn, ...options })`
|
|
342
|
+
## Infinite Queries
|
|
447
343
|
|
|
448
|
-
**Before (v4):**
|
|
449
344
|
```tsx
|
|
450
|
-
|
|
451
|
-
```
|
|
345
|
+
import { useInfiniteQuery } from '@tanstack/react-query'
|
|
452
346
|
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
347
|
+
function InfiniteList() {
|
|
348
|
+
const {
|
|
349
|
+
data,
|
|
350
|
+
fetchNextPage,
|
|
351
|
+
fetchPreviousPage,
|
|
352
|
+
hasNextPage,
|
|
353
|
+
hasPreviousPage,
|
|
354
|
+
isFetchingNextPage,
|
|
355
|
+
isFetchingPreviousPage,
|
|
356
|
+
} = useInfiniteQuery({
|
|
357
|
+
queryKey: ['projects'],
|
|
358
|
+
queryFn: async ({ pageParam }) => {
|
|
359
|
+
const res = await fetch(`/api/projects?cursor=${pageParam}`)
|
|
360
|
+
return res.json()
|
|
361
|
+
},
|
|
362
|
+
initialPageParam: 0,
|
|
363
|
+
getNextPageParam: (lastPage, allPages, lastPageParam) => {
|
|
364
|
+
return lastPage.nextCursor ?? undefined // undefined = no more pages
|
|
365
|
+
},
|
|
366
|
+
getPreviousPageParam: (firstPage, allPages, firstPageParam) => {
|
|
367
|
+
return firstPage.prevCursor ?? undefined
|
|
368
|
+
},
|
|
369
|
+
maxPages: 3, // Keep max 3 pages in cache (for performance)
|
|
370
|
+
})
|
|
371
|
+
|
|
372
|
+
return (
|
|
373
|
+
<div>
|
|
374
|
+
{data.pages.map((page) =>
|
|
375
|
+
page.items.map((item) => <Item key={item.id} item={item} />)
|
|
376
|
+
)}
|
|
377
|
+
<button
|
|
378
|
+
onClick={() => fetchNextPage()}
|
|
379
|
+
disabled={!hasNextPage || isFetchingNextPage}
|
|
380
|
+
>
|
|
381
|
+
{isFetchingNextPage ? 'Loading...' : hasNextPage ? 'Load More' : 'No more'}
|
|
382
|
+
</button>
|
|
383
|
+
</div>
|
|
384
|
+
)
|
|
385
|
+
}
|
|
460
386
|
```
|
|
461
387
|
|
|
462
|
-
|
|
463
|
-
**Error**: Callbacks don't run, TypeScript errors
|
|
464
|
-
**Source**: [v5 Breaking Changes](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#callbacks-on-usequery-and-queryobserver-have-been-removed)
|
|
465
|
-
**Why It Happens**: onSuccess, onError, onSettled removed from queries (still work in mutations)
|
|
466
|
-
**Prevention**: Use `useEffect` for side effects, or move logic to mutation callbacks
|
|
388
|
+
## Parallel Queries
|
|
467
389
|
|
|
468
|
-
**Before (v4):**
|
|
469
390
|
```tsx
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
queryFn:
|
|
473
|
-
|
|
474
|
-
console.log('Todos loaded:', data)
|
|
475
|
-
},
|
|
476
|
-
})
|
|
477
|
-
```
|
|
391
|
+
// Multiple independent queries run in parallel automatically
|
|
392
|
+
function Dashboard() {
|
|
393
|
+
const usersQuery = useQuery({ queryKey: ['users'], queryFn: fetchUsers })
|
|
394
|
+
const projectsQuery = useQuery({ queryKey: ['projects'], queryFn: fetchProjects })
|
|
478
395
|
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
396
|
+
// Both fetch simultaneously
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// Dynamic parallel queries with useQueries
|
|
400
|
+
function UserProjects({ userIds }) {
|
|
401
|
+
const queries = useQueries({
|
|
402
|
+
queries: userIds.map((id) => ({
|
|
403
|
+
queryKey: ['user', id],
|
|
404
|
+
queryFn: () => fetchUser(id),
|
|
405
|
+
})),
|
|
406
|
+
combine: (results) => ({
|
|
407
|
+
data: results.map(r => r.data),
|
|
408
|
+
pending: results.some(r => r.isPending),
|
|
409
|
+
}),
|
|
410
|
+
})
|
|
411
|
+
}
|
|
487
412
|
```
|
|
488
413
|
|
|
489
|
-
|
|
490
|
-
**Error**: UI shows wrong loading state
|
|
491
|
-
**Source**: [v5 Migration: isLoading renamed](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#isloading-and-isfetching-flags)
|
|
492
|
-
**Why It Happens**: `status: 'loading'` renamed to `status: 'pending'`, `isLoading` meaning changed
|
|
493
|
-
**Prevention**: Use `isPending` for initial load, `isLoading` for "pending AND fetching"
|
|
414
|
+
## Dependent Queries
|
|
494
415
|
|
|
495
|
-
**Before (v4):**
|
|
496
416
|
```tsx
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
417
|
+
// Sequential queries using enabled
|
|
418
|
+
function UserPosts({ userId }) {
|
|
419
|
+
const userQuery = useQuery({
|
|
420
|
+
queryKey: ['user', userId],
|
|
421
|
+
queryFn: () => fetchUser(userId),
|
|
422
|
+
})
|
|
500
423
|
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
424
|
+
const postsQuery = useQuery({
|
|
425
|
+
queryKey: ['posts', userId],
|
|
426
|
+
queryFn: () => fetchPostsByUser(userId),
|
|
427
|
+
enabled: !!userQuery.data, // Only run when user is loaded
|
|
428
|
+
})
|
|
429
|
+
}
|
|
506
430
|
```
|
|
507
431
|
|
|
508
|
-
|
|
509
|
-
**Error**: `cacheTime is not a valid option`
|
|
510
|
-
**Source**: [v5 Migration: gcTime](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#cachetime-has-been-replaced-by-gctime)
|
|
511
|
-
**Why It Happens**: Renamed to better reflect "garbage collection time"
|
|
512
|
-
**Prevention**: Use `gcTime` instead of `cacheTime`
|
|
432
|
+
## Paginated Queries
|
|
513
433
|
|
|
514
|
-
**Before (v4):**
|
|
515
434
|
```tsx
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
queryFn: fetchTodos,
|
|
519
|
-
cacheTime: 1000 * 60 * 60,
|
|
520
|
-
})
|
|
521
|
-
```
|
|
435
|
+
function PaginatedList() {
|
|
436
|
+
const [page, setPage] = useState(1)
|
|
522
437
|
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
438
|
+
const { data, isPlaceholderData } = useQuery({
|
|
439
|
+
queryKey: ['todos', page],
|
|
440
|
+
queryFn: () => fetchTodos(page),
|
|
441
|
+
placeholderData: (previousData) => previousData, // Keep showing old data
|
|
442
|
+
})
|
|
443
|
+
|
|
444
|
+
return (
|
|
445
|
+
<div style={{ opacity: isPlaceholderData ? 0.5 : 1 }}>
|
|
446
|
+
{data.items.map(item => <Item key={item.id} item={item} />)}
|
|
447
|
+
<button
|
|
448
|
+
onClick={() => setPage(p => p + 1)}
|
|
449
|
+
disabled={isPlaceholderData || !data.hasMore}
|
|
450
|
+
>
|
|
451
|
+
Next
|
|
452
|
+
</button>
|
|
453
|
+
</div>
|
|
454
|
+
)
|
|
455
|
+
}
|
|
530
456
|
```
|
|
531
457
|
|
|
532
|
-
|
|
533
|
-
**Error**: Type error, enabled option not available
|
|
534
|
-
**Source**: [GitHub Discussion #6206](https://github.com/TanStack/query/discussions/6206)
|
|
535
|
-
**Why It Happens**: Suspense guarantees data is available, can't conditionally disable
|
|
536
|
-
**Prevention**: Use conditional rendering instead of `enabled` option
|
|
458
|
+
## Suspense Integration
|
|
537
459
|
|
|
538
|
-
**Before (v4/incorrect):**
|
|
539
460
|
```tsx
|
|
540
|
-
useSuspenseQuery
|
|
541
|
-
queryKey: ['todo', id],
|
|
542
|
-
queryFn: () => fetchTodo(id),
|
|
543
|
-
enabled: !!id, // ❌ Not allowed
|
|
544
|
-
})
|
|
545
|
-
```
|
|
461
|
+
import { useSuspenseQuery, useSuspenseInfiniteQuery } from '@tanstack/react-query'
|
|
546
462
|
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
// Conditional rendering:
|
|
550
|
-
{id ? (
|
|
551
|
-
<TodoComponent id={id} />
|
|
552
|
-
) : (
|
|
553
|
-
<div>No ID selected</div>
|
|
554
|
-
)}
|
|
555
|
-
|
|
556
|
-
// Inside TodoComponent:
|
|
557
|
-
function TodoComponent({ id }: { id: number }) {
|
|
463
|
+
// Component will suspend until data is loaded
|
|
464
|
+
function TodoList() {
|
|
558
465
|
const { data } = useSuspenseQuery({
|
|
559
|
-
queryKey: ['
|
|
560
|
-
queryFn:
|
|
561
|
-
// No enabled option needed
|
|
466
|
+
queryKey: ['todos'],
|
|
467
|
+
queryFn: fetchTodos,
|
|
562
468
|
})
|
|
563
|
-
|
|
469
|
+
// data is guaranteed to be defined here
|
|
470
|
+
return <ul>{data.map(todo => <li key={todo.id}>{todo.title}</li>)}</ul>
|
|
564
471
|
}
|
|
565
|
-
```
|
|
566
472
|
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
queryFn: ({ pageParam = 0 }) => fetchProjects(pageParam),
|
|
578
|
-
getNextPageParam: (lastPage) => lastPage.nextCursor,
|
|
579
|
-
})
|
|
580
|
-
```
|
|
473
|
+
// Wrap with Suspense boundary
|
|
474
|
+
function App() {
|
|
475
|
+
return (
|
|
476
|
+
<ErrorBoundary fallback={<Error />}>
|
|
477
|
+
<Suspense fallback={<Loading />}>
|
|
478
|
+
<TodoList />
|
|
479
|
+
</Suspense>
|
|
480
|
+
</ErrorBoundary>
|
|
481
|
+
)
|
|
482
|
+
}
|
|
581
483
|
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
})
|
|
484
|
+
// Multiple suspense queries (fetch in parallel)
|
|
485
|
+
function Dashboard() {
|
|
486
|
+
const [{ data: users }, { data: projects }] = useSuspenseQueries({
|
|
487
|
+
queries: [
|
|
488
|
+
{ queryKey: ['users'], queryFn: fetchUsers },
|
|
489
|
+
{ queryKey: ['projects'], queryFn: fetchProjects },
|
|
490
|
+
],
|
|
491
|
+
})
|
|
492
|
+
}
|
|
590
493
|
```
|
|
591
494
|
|
|
592
|
-
|
|
593
|
-
**Error**: `keepPreviousData is not a valid option`
|
|
594
|
-
**Source**: [v5 Migration: placeholderData](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#removed-keeppreviousdata-in-favor-of-placeholderdata-identity-function)
|
|
595
|
-
**Why It Happens**: Replaced with more flexible `placeholderData` function
|
|
596
|
-
**Prevention**: Use `placeholderData: keepPreviousData` helper
|
|
597
|
-
|
|
598
|
-
**Before (v4):**
|
|
599
|
-
```tsx
|
|
600
|
-
useQuery({
|
|
601
|
-
queryKey: ['todos', page],
|
|
602
|
-
queryFn: () => fetchTodos(page),
|
|
603
|
-
keepPreviousData: true,
|
|
604
|
-
})
|
|
605
|
-
```
|
|
495
|
+
## Prefetching
|
|
606
496
|
|
|
607
|
-
**After (v5):**
|
|
608
497
|
```tsx
|
|
609
|
-
|
|
498
|
+
const queryClient = useQueryClient()
|
|
610
499
|
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
500
|
+
// Prefetch on hover
|
|
501
|
+
function TodoLink({ todoId }) {
|
|
502
|
+
const prefetch = () => {
|
|
503
|
+
queryClient.prefetchQuery({
|
|
504
|
+
queryKey: ['todo', todoId],
|
|
505
|
+
queryFn: () => fetchTodo(todoId),
|
|
506
|
+
staleTime: 5000, // Only prefetch if data older than 5s
|
|
507
|
+
})
|
|
508
|
+
}
|
|
617
509
|
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
510
|
+
return (
|
|
511
|
+
<Link to={`/todos/${todoId}`} onMouseEnter={prefetch}>
|
|
512
|
+
Todo {todoId}
|
|
513
|
+
</Link>
|
|
514
|
+
)
|
|
515
|
+
}
|
|
623
516
|
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
queryFn: async () => {
|
|
629
|
-
if (Math.random() > 0.5) throw 'custom error string'
|
|
630
|
-
return data
|
|
631
|
-
},
|
|
517
|
+
// Prefetch in route loader (TanStack Router integration)
|
|
518
|
+
export const Route = createFileRoute('/todos/$todoId')({
|
|
519
|
+
loader: ({ context: { queryClient }, params: { todoId } }) =>
|
|
520
|
+
queryClient.ensureQueryData(todoQueryOptions(todoId)),
|
|
632
521
|
})
|
|
633
|
-
// error: unknown
|
|
634
|
-
```
|
|
635
522
|
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
return data
|
|
643
|
-
},
|
|
644
|
-
})
|
|
645
|
-
// error: string | null
|
|
646
|
-
|
|
647
|
-
// Or better: always throw Error objects
|
|
648
|
-
const { error } = useQuery({
|
|
649
|
-
queryKey: ['data'],
|
|
650
|
-
queryFn: async () => {
|
|
651
|
-
if (Math.random() > 0.5) throw new Error('custom error')
|
|
652
|
-
return data
|
|
653
|
-
},
|
|
523
|
+
// Prefetch infinite queries
|
|
524
|
+
queryClient.prefetchInfiniteQuery({
|
|
525
|
+
queryKey: ['projects'],
|
|
526
|
+
queryFn: fetchProjects,
|
|
527
|
+
initialPageParam: 0,
|
|
528
|
+
pages: 3, // Prefetch first 3 pages
|
|
654
529
|
})
|
|
655
|
-
// error: Error | null (default)
|
|
656
530
|
```
|
|
657
531
|
|
|
658
|
-
|
|
659
|
-
**Error**: `Hydration failed because the initial UI does not match what was rendered on the server`
|
|
660
|
-
**Source**: [GitHub Issue #9642](https://github.com/TanStack/query/issues/9642)
|
|
661
|
-
**Affects**: v5.82.0+ with streaming SSR (void prefetch pattern)
|
|
662
|
-
**Why It Happens**: Race condition where `hydrate()` resolves synchronously but `query.fetch()` creates async retryer, causing isFetching/isStale mismatch between server and client
|
|
663
|
-
**Prevention**: Don't conditionally render based on `fetchStatus` with `useSuspenseQuery` and streaming prefetch, OR await prefetch instead of void pattern
|
|
664
|
-
|
|
665
|
-
**Before (causes hydration error):**
|
|
666
|
-
```tsx
|
|
667
|
-
// Server: void prefetch
|
|
668
|
-
streamingQueryClient.prefetchQuery({ queryKey: ['data'], queryFn: getData });
|
|
532
|
+
## SSR & Hydration
|
|
669
533
|
|
|
670
|
-
|
|
671
|
-
const { data, isFetching } = useSuspenseQuery({ queryKey: ['data'], queryFn: getData });
|
|
672
|
-
return <>{data && <div>{data}</div>} {isFetching && <Loading />}</>;
|
|
673
|
-
```
|
|
534
|
+
### Server-Side Prefetching
|
|
674
535
|
|
|
675
|
-
**After (workaround):**
|
|
676
536
|
```tsx
|
|
677
|
-
//
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
// Option 2: Don't render based on fetchStatus with Suspense
|
|
681
|
-
const { data } = useSuspenseQuery({ queryKey: ['data'], queryFn: getData });
|
|
682
|
-
return <div>{data}</div>; // No conditional on isFetching
|
|
683
|
-
```
|
|
684
|
-
|
|
685
|
-
**Status**: Known issue, being investigated by maintainers. Requires implementation of `getServerSnapshot` in useSyncExternalStore.
|
|
537
|
+
// Server component or loader
|
|
538
|
+
import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query'
|
|
686
539
|
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
**Source**: [GitHub Issue #9399](https://github.com/TanStack/query/issues/9399)
|
|
690
|
-
**Affects**: v5.x with server-side prefetching
|
|
691
|
-
**Why It Happens**: `tryResolveSync` detects resolved promises in RSC payload and extracts data synchronously during hydration, bypassing normal pending state
|
|
692
|
-
**Prevention**: Use `useSuspenseQuery` instead of `useQuery` for SSR, or avoid conditional rendering based on `isLoading`
|
|
540
|
+
async function getServerSideProps() {
|
|
541
|
+
const queryClient = new QueryClient()
|
|
693
542
|
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
await queryClient.prefetchQuery({ queryKey: ['todos'], queryFn: fetchTodos });
|
|
543
|
+
await queryClient.prefetchQuery({
|
|
544
|
+
queryKey: ['todos'],
|
|
545
|
+
queryFn: fetchTodos,
|
|
546
|
+
})
|
|
699
547
|
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
548
|
+
return {
|
|
549
|
+
props: {
|
|
550
|
+
dehydratedState: dehydrate(queryClient),
|
|
551
|
+
},
|
|
552
|
+
}
|
|
705
553
|
}
|
|
706
|
-
```
|
|
707
554
|
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
555
|
+
function Page({ dehydratedState }) {
|
|
556
|
+
return (
|
|
557
|
+
<HydrationBoundary state={dehydratedState}>
|
|
558
|
+
<Todos />
|
|
559
|
+
</HydrationBoundary>
|
|
560
|
+
)
|
|
714
561
|
}
|
|
715
562
|
```
|
|
716
563
|
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
### Issue #11: refetchOnMount Not Respected for Errored Queries
|
|
720
|
-
**Error**: Queries refetch on mount despite `refetchOnMount: false`
|
|
721
|
-
**Source**: [GitHub Issue #10018](https://github.com/TanStack/query/issues/10018)
|
|
722
|
-
**Affects**: v5.90.16+
|
|
723
|
-
**Why It Happens**: Errored queries with no data are always treated as stale. This is intentional to avoid permanently showing error states
|
|
724
|
-
**Prevention**: Use `retryOnMount: false` instead of (or in addition to) `refetchOnMount: false`
|
|
725
|
-
|
|
726
|
-
**Before (refetches despite setting):**
|
|
727
|
-
```tsx
|
|
728
|
-
const { data, error } = useQuery({
|
|
729
|
-
queryKey: ['data'],
|
|
730
|
-
queryFn: () => { throw new Error('Fails') },
|
|
731
|
-
refetchOnMount: false, // Ignored when query is in error state
|
|
732
|
-
retry: 0,
|
|
733
|
-
});
|
|
734
|
-
// Query refetches every time component mounts
|
|
735
|
-
```
|
|
564
|
+
### Streaming SSR (React Server Components)
|
|
736
565
|
|
|
737
|
-
**After (correct):**
|
|
738
566
|
```tsx
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
queryFn: failingFetch,
|
|
742
|
-
refetchOnMount: false,
|
|
743
|
-
retryOnMount: false, // ✅ Prevents refetch on mount for errored queries
|
|
744
|
-
retry: 0,
|
|
745
|
-
});
|
|
746
|
-
```
|
|
567
|
+
import { dehydrate, HydrationBoundary } from '@tanstack/react-query'
|
|
568
|
+
import { makeQueryClient } from './query-client'
|
|
747
569
|
|
|
748
|
-
|
|
570
|
+
export default async function Page() {
|
|
571
|
+
const queryClient = makeQueryClient()
|
|
749
572
|
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
**Prevention**: Update all mutation callbacks to accept 4 parameters instead of 3
|
|
573
|
+
// Prefetch on server
|
|
574
|
+
await queryClient.prefetchQuery({
|
|
575
|
+
queryKey: ['todos'],
|
|
576
|
+
queryFn: fetchTodos,
|
|
577
|
+
})
|
|
756
578
|
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
},
|
|
764
|
-
onSuccess: (data, variables, context) => {
|
|
765
|
-
// Same issue
|
|
766
|
-
}
|
|
767
|
-
});
|
|
579
|
+
return (
|
|
580
|
+
<HydrationBoundary state={dehydrate(queryClient)}>
|
|
581
|
+
<TodoList />
|
|
582
|
+
</HydrationBoundary>
|
|
583
|
+
)
|
|
584
|
+
}
|
|
768
585
|
```
|
|
769
586
|
|
|
770
|
-
|
|
771
|
-
```tsx
|
|
772
|
-
useMutation({
|
|
773
|
-
mutationFn: addTodo,
|
|
774
|
-
onError: (error, variables, onMutateResult, context) => {
|
|
775
|
-
// onMutateResult = return value from onMutate
|
|
776
|
-
// context = mutation function context
|
|
777
|
-
},
|
|
778
|
-
onSuccess: (data, variables, onMutateResult, context) => {
|
|
779
|
-
// Correct signature with 4 parameters
|
|
780
|
-
}
|
|
781
|
-
});
|
|
782
|
-
```
|
|
587
|
+
## QueryClient API
|
|
783
588
|
|
|
784
|
-
|
|
589
|
+
```tsx
|
|
590
|
+
const queryClient = useQueryClient()
|
|
785
591
|
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
**Source**: [GitHub Issue #9871](https://github.com/TanStack/query/issues/9871) | Fixed in [PR #9872](https://github.com/TanStack/query/pull/9872)
|
|
789
|
-
**Affects**: v5.90.8 only (fixed in v5.90.9)
|
|
790
|
-
**Why It Happens**: Partial query matching broke TypeScript types for readonly query keys (using `as const`)
|
|
791
|
-
**Prevention**: Upgrade to v5.90.9+ or use type assertions if stuck on v5.90.8
|
|
592
|
+
// Get cached data
|
|
593
|
+
queryClient.getQueryData(['todos'])
|
|
792
594
|
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
return id ? ['todos', id] as const : ['todos'] as const;
|
|
797
|
-
}
|
|
798
|
-
// Type: readonly ['todos', string] | readonly ['todos']
|
|
799
|
-
|
|
800
|
-
useMutation({
|
|
801
|
-
mutationFn: addTodo,
|
|
802
|
-
onSuccess: () => {
|
|
803
|
-
queryClient.invalidateQueries({
|
|
804
|
-
queryKey: todoQueryKey('123')
|
|
805
|
-
// Error: readonly ['todos', string] not assignable to ['todos', string]
|
|
806
|
-
});
|
|
807
|
-
}
|
|
808
|
-
});
|
|
809
|
-
```
|
|
595
|
+
// Set cached data
|
|
596
|
+
queryClient.setQueryData(['todos'], updatedTodos)
|
|
597
|
+
queryClient.setQueryData(['todos'], (old) => [...old, newTodo])
|
|
810
598
|
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
// Works correctly with readonly types
|
|
814
|
-
queryClient.invalidateQueries({
|
|
815
|
-
queryKey: todoQueryKey('123') // ✅ No type error
|
|
816
|
-
});
|
|
817
|
-
```
|
|
599
|
+
// Get query state
|
|
600
|
+
queryClient.getQueryState(['todos'])
|
|
818
601
|
|
|
819
|
-
|
|
602
|
+
// Check if fetching
|
|
603
|
+
queryClient.isFetching({ queryKey: ['todos'] })
|
|
604
|
+
queryClient.isMutating()
|
|
820
605
|
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
**Source**: [GitHub Issue #9825](https://github.com/TanStack/query/issues/9825)
|
|
824
|
-
**Affects**: All v5.x versions
|
|
825
|
-
**Why It Happens**: Fuzzy mutation key matching prevents guaranteed type inference (same issue as `queryClient.getQueryCache().find()`)
|
|
826
|
-
**Prevention**: Explicitly cast types in the `select` callback
|
|
606
|
+
// Cancel queries
|
|
607
|
+
queryClient.cancelQueries({ queryKey: ['todos'] })
|
|
827
608
|
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
const addTodo = useMutation({
|
|
831
|
-
mutationKey: ['addTodo'],
|
|
832
|
-
mutationFn: (todo: Todo) => api.addTodo(todo),
|
|
833
|
-
});
|
|
834
|
-
|
|
835
|
-
const pendingTodos = useMutationState({
|
|
836
|
-
filters: { mutationKey: ['addTodo'], status: 'pending' },
|
|
837
|
-
select: (mutation) => {
|
|
838
|
-
return mutation.state.variables; // Type: unknown
|
|
839
|
-
},
|
|
840
|
-
});
|
|
841
|
-
```
|
|
609
|
+
// Invalidate (marks stale, refetches active)
|
|
610
|
+
queryClient.invalidateQueries({ queryKey: ['todos'] })
|
|
842
611
|
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
const pendingTodos = useMutationState({
|
|
846
|
-
filters: { mutationKey: ['addTodo'], status: 'pending' },
|
|
847
|
-
select: (mutation) => mutation.state.variables as Todo,
|
|
848
|
-
});
|
|
849
|
-
// Or cast the entire state:
|
|
850
|
-
select: (mutation) => mutation.state as MutationState<Todo, Error, Todo, unknown>
|
|
851
|
-
```
|
|
612
|
+
// Refetch (force refetch even if fresh)
|
|
613
|
+
queryClient.refetchQueries({ queryKey: ['todos'] })
|
|
852
614
|
|
|
853
|
-
|
|
615
|
+
// Remove from cache
|
|
616
|
+
queryClient.removeQueries({ queryKey: ['todos'] })
|
|
854
617
|
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
**Source**: [GitHub Issue #9798](https://github.com/TanStack/query/issues/9798)
|
|
858
|
-
**Affects**: Development only (React StrictMode)
|
|
859
|
-
**Why It Happens**: StrictMode causes double mount/unmount. When `useQuery` unmounts and is the last observer, it cancels the query even if `fetchQuery()` is also running
|
|
860
|
-
**Prevention**: This is expected development-only behavior. Doesn't affect production
|
|
618
|
+
// Reset to initial state
|
|
619
|
+
queryClient.resetQueries({ queryKey: ['todos'] })
|
|
861
620
|
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
async function loadData() {
|
|
865
|
-
try {
|
|
866
|
-
const data = await queryClient.fetchQuery({
|
|
867
|
-
queryKey: ['data'],
|
|
868
|
-
queryFn: fetchData,
|
|
869
|
-
});
|
|
870
|
-
console.log('Loaded:', data); // Never logs in StrictMode
|
|
871
|
-
} catch (error) {
|
|
872
|
-
console.error('Failed:', error); // CancelledError
|
|
873
|
-
}
|
|
874
|
-
}
|
|
621
|
+
// Clear entire cache
|
|
622
|
+
queryClient.clear()
|
|
875
623
|
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
}
|
|
880
|
-
```
|
|
624
|
+
// Prefetch
|
|
625
|
+
queryClient.prefetchQuery({ queryKey: ['todos'], queryFn: fetchTodos })
|
|
626
|
+
queryClient.ensureQueryData({ queryKey: ['todos'], queryFn: fetchTodos })
|
|
881
627
|
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
queryKey: ['data'],
|
|
887
|
-
queryFn: fetchData,
|
|
888
|
-
staleTime: Infinity, // Keeps query active
|
|
889
|
-
});
|
|
628
|
+
// Get/set defaults
|
|
629
|
+
queryClient.setQueryDefaults(['todos'], { staleTime: 10000 })
|
|
630
|
+
queryClient.getQueryDefaults(['todos'])
|
|
631
|
+
queryClient.setMutationDefaults(['addTodo'], { mutationFn: addTodo })
|
|
890
632
|
```
|
|
891
633
|
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
### Issue #16: invalidateQueries Only Refetches Active Queries
|
|
895
|
-
**Error**: Inactive queries not refetching despite `invalidateQueries()` call
|
|
896
|
-
**Source**: [GitHub Issue #9531](https://github.com/TanStack/query/issues/9531)
|
|
897
|
-
**Affects**: All v5.x versions
|
|
898
|
-
**Why It Happens**: Documentation was misleading - `invalidateQueries()` only refetches "active" queries by default, not "all" queries
|
|
899
|
-
**Prevention**: Use `refetchType: 'all'` to force refetch of inactive queries
|
|
634
|
+
## Testing
|
|
900
635
|
|
|
901
|
-
**Default behavior:**
|
|
902
636
|
```tsx
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
```
|
|
637
|
+
import { renderHook, waitFor } from '@testing-library/react'
|
|
638
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
906
639
|
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
640
|
+
function createWrapper() {
|
|
641
|
+
const queryClient = new QueryClient({
|
|
642
|
+
defaultOptions: {
|
|
643
|
+
queries: {
|
|
644
|
+
retry: false, // Don't retry in tests
|
|
645
|
+
gcTime: Infinity, // Prevent garbage collection during tests
|
|
646
|
+
},
|
|
647
|
+
},
|
|
648
|
+
})
|
|
649
|
+
return ({ children }) => (
|
|
650
|
+
<QueryClientProvider client={queryClient}>
|
|
651
|
+
{children}
|
|
652
|
+
</QueryClientProvider>
|
|
653
|
+
)
|
|
654
|
+
}
|
|
914
655
|
|
|
915
|
-
|
|
656
|
+
test('fetches todos', async () => {
|
|
657
|
+
const { result } = renderHook(() => useQuery({
|
|
658
|
+
queryKey: ['todos'],
|
|
659
|
+
queryFn: fetchTodos,
|
|
660
|
+
}), { wrapper: createWrapper() })
|
|
916
661
|
|
|
917
|
-
|
|
662
|
+
await waitFor(() => expect(result.current.isSuccess).toBe(true))
|
|
663
|
+
expect(result.current.data).toEqual(expectedTodos)
|
|
664
|
+
})
|
|
918
665
|
|
|
919
|
-
|
|
666
|
+
// Mock with setQueryData for component tests
|
|
667
|
+
test('renders todos', () => {
|
|
668
|
+
const queryClient = new QueryClient()
|
|
669
|
+
queryClient.setQueryData(['todos'], mockTodos)
|
|
920
670
|
|
|
921
|
-
|
|
671
|
+
render(
|
|
672
|
+
<QueryClientProvider client={queryClient}>
|
|
673
|
+
<TodoList />
|
|
674
|
+
</QueryClientProvider>
|
|
675
|
+
)
|
|
922
676
|
|
|
923
|
-
|
|
677
|
+
expect(screen.getByText('Todo 1')).toBeInTheDocument()
|
|
678
|
+
})
|
|
679
|
+
```
|
|
924
680
|
|
|
925
|
-
|
|
926
|
-
**Applies to**: v5.27.3+
|
|
681
|
+
## TypeScript Patterns
|
|
927
682
|
|
|
928
|
-
|
|
683
|
+
### Typing Query Functions
|
|
929
684
|
|
|
930
|
-
**Example of unexpected behavior:**
|
|
931
685
|
```tsx
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
queryFn: fetchTodos,
|
|
937
|
-
staleTime: 5000, // Applied initially
|
|
938
|
-
});
|
|
686
|
+
interface Todo {
|
|
687
|
+
id: number
|
|
688
|
+
title: string
|
|
689
|
+
completed: boolean
|
|
939
690
|
}
|
|
940
691
|
|
|
941
|
-
//
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
}
|
|
948
|
-
}
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
**Recommended approach:**
|
|
952
|
-
```tsx
|
|
953
|
-
// Write options as functions that reference latest values
|
|
954
|
-
const getStaleTime = () => shouldUseLongCache ? 60000 : 5000;
|
|
692
|
+
// Type is inferred from queryFn return type
|
|
693
|
+
const { data } = useQuery({
|
|
694
|
+
queryKey: ['todos'],
|
|
695
|
+
queryFn: async (): Promise<Todo[]> => {
|
|
696
|
+
const res = await fetch('/api/todos')
|
|
697
|
+
return res.json()
|
|
698
|
+
},
|
|
699
|
+
})
|
|
700
|
+
// data: Todo[] | undefined
|
|
955
701
|
|
|
956
|
-
|
|
702
|
+
// With select
|
|
703
|
+
const { data } = useQuery({
|
|
957
704
|
queryKey: ['todos'],
|
|
958
705
|
queryFn: fetchTodos,
|
|
959
|
-
|
|
960
|
-
})
|
|
706
|
+
select: (data): string[] => data.map(t => t.title),
|
|
707
|
+
})
|
|
708
|
+
// data: string[] | undefined
|
|
961
709
|
```
|
|
962
710
|
|
|
963
|
-
###
|
|
964
|
-
|
|
965
|
-
**Source**: [Avoiding Common Mistakes with TanStack Query](https://www.buncolak.com/posts/avoiding-common-mistakes-with-tanstack-query-part-1/) | **Confidence**: HIGH
|
|
966
|
-
|
|
967
|
-
The `refetch()` function should ONLY be used for refreshing with the same parameters (like a manual "reload" button). For new parameters (filters, page numbers, search terms, etc.), include them in the query key instead.
|
|
968
|
-
|
|
969
|
-
**Anti-pattern:**
|
|
970
|
-
```tsx
|
|
971
|
-
// ❌ Wrong - using refetch() for different parameters
|
|
972
|
-
const [page, setPage] = useState(1);
|
|
973
|
-
const { data, refetch } = useQuery({
|
|
974
|
-
queryKey: ['todos'], // Same key for all pages
|
|
975
|
-
queryFn: () => fetchTodos(page),
|
|
976
|
-
});
|
|
977
|
-
|
|
978
|
-
// This refetches with OLD page value, not new one
|
|
979
|
-
<button onClick={() => { setPage(2); refetch(); }}>Next</button>
|
|
980
|
-
```
|
|
711
|
+
### Typing Errors
|
|
981
712
|
|
|
982
|
-
**Correct pattern:**
|
|
983
713
|
```tsx
|
|
984
|
-
//
|
|
985
|
-
const
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
// Query automatically refetches when page changes
|
|
990
|
-
});
|
|
714
|
+
// Default error type is Error
|
|
715
|
+
const { error } = useQuery<Todo[], AxiosError>({
|
|
716
|
+
queryKey: ['todos'],
|
|
717
|
+
queryFn: fetchTodos,
|
|
718
|
+
})
|
|
991
719
|
|
|
992
|
-
|
|
720
|
+
// Or register globally
|
|
721
|
+
declare module '@tanstack/react-query' {
|
|
722
|
+
interface Register {
|
|
723
|
+
defaultError: AxiosError
|
|
724
|
+
}
|
|
725
|
+
}
|
|
993
726
|
```
|
|
994
727
|
|
|
995
|
-
|
|
728
|
+
### Query Options Pattern (Recommended)
|
|
729
|
+
|
|
996
730
|
```tsx
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
731
|
+
import { queryOptions, infiniteQueryOptions } from '@tanstack/react-query'
|
|
732
|
+
|
|
733
|
+
export const todosOptions = queryOptions({
|
|
734
|
+
queryKey: ['todos'] as const,
|
|
1000
735
|
queryFn: fetchTodos,
|
|
1001
|
-
|
|
736
|
+
staleTime: 5000,
|
|
737
|
+
})
|
|
1002
738
|
|
|
1003
|
-
|
|
739
|
+
export const todoOptions = (id: string) =>
|
|
740
|
+
queryOptions({
|
|
741
|
+
queryKey: ['todos', id] as const,
|
|
742
|
+
queryFn: () => fetchTodo(id),
|
|
743
|
+
enabled: !!id,
|
|
744
|
+
})
|
|
745
|
+
|
|
746
|
+
// Full type inference everywhere
|
|
747
|
+
const { data } = useQuery(todosOptions)
|
|
748
|
+
const { data } = useSuspenseQuery(todoOptions('123'))
|
|
749
|
+
await queryClient.ensureQueryData(todosOptions)
|
|
750
|
+
queryClient.invalidateQueries({ queryKey: todosOptions.queryKey })
|
|
1004
751
|
```
|
|
1005
752
|
|
|
1006
|
-
|
|
753
|
+
## Advanced Patterns
|
|
1007
754
|
|
|
1008
|
-
|
|
755
|
+
### Window Focus Refetching
|
|
1009
756
|
|
|
1010
|
-
**Dependent Queries** (Query B waits for Query A):
|
|
1011
757
|
```tsx
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
758
|
+
// Disable globally
|
|
759
|
+
const queryClient = new QueryClient({
|
|
760
|
+
defaultOptions: {
|
|
761
|
+
queries: { refetchOnWindowFocus: false },
|
|
762
|
+
},
|
|
1016
763
|
})
|
|
1017
|
-
```
|
|
1018
764
|
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
765
|
+
// Custom focus manager
|
|
766
|
+
import { focusManager } from '@tanstack/react-query'
|
|
767
|
+
|
|
768
|
+
// For React Native
|
|
769
|
+
focusManager.setEventListener((handleFocus) => {
|
|
770
|
+
const subscription = AppState.addEventListener('change', (state) => {
|
|
771
|
+
handleFocus(state === 'active')
|
|
772
|
+
})
|
|
773
|
+
return () => subscription.remove()
|
|
1023
774
|
})
|
|
1024
775
|
```
|
|
1025
776
|
|
|
1026
|
-
|
|
1027
|
-
```tsx
|
|
1028
|
-
queryClient.prefetchQuery({ queryKey: ['todo', id], queryFn: () => fetchTodo(id) })
|
|
1029
|
-
```
|
|
777
|
+
### Network Mode
|
|
1030
778
|
|
|
1031
|
-
**Infinite Scroll** (useInfiniteQuery):
|
|
1032
779
|
```tsx
|
|
1033
|
-
|
|
1034
|
-
queryKey: ['todos'
|
|
1035
|
-
queryFn:
|
|
1036
|
-
|
|
1037
|
-
|
|
780
|
+
useQuery({
|
|
781
|
+
queryKey: ['todos'],
|
|
782
|
+
queryFn: fetchTodos,
|
|
783
|
+
// 'online' (default): only fetch when online
|
|
784
|
+
// 'always': always fetch (useful for local-first)
|
|
785
|
+
// 'offlineFirst': try fetch, use cache if offline
|
|
786
|
+
networkMode: 'offlineFirst',
|
|
1038
787
|
})
|
|
1039
788
|
```
|
|
1040
789
|
|
|
1041
|
-
|
|
790
|
+
### Query Cancellation
|
|
791
|
+
|
|
1042
792
|
```tsx
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
793
|
+
useQuery({
|
|
794
|
+
queryKey: ['todos'],
|
|
795
|
+
queryFn: async ({ signal }) => {
|
|
796
|
+
// signal is AbortSignal - automatically cancelled on unmount or key change
|
|
797
|
+
const res = await fetch('/api/todos', { signal })
|
|
798
|
+
return res.json()
|
|
799
|
+
},
|
|
800
|
+
})
|
|
801
|
+
|
|
802
|
+
// Manual cancellation
|
|
803
|
+
queryClient.cancelQueries({ queryKey: ['todos'] })
|
|
1047
804
|
```
|
|
1048
805
|
|
|
1049
|
-
|
|
806
|
+
### Persistence
|
|
807
|
+
|
|
1050
808
|
```tsx
|
|
1051
|
-
|
|
1052
|
-
|
|
809
|
+
import { persistQueryClient } from '@tanstack/react-query-persist-client'
|
|
810
|
+
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
|
|
1053
811
|
|
|
1054
|
-
|
|
812
|
+
const persister = createSyncStoragePersister({
|
|
813
|
+
storage: window.localStorage,
|
|
814
|
+
})
|
|
1055
815
|
|
|
1056
|
-
|
|
816
|
+
persistQueryClient({
|
|
817
|
+
queryClient,
|
|
818
|
+
persister,
|
|
819
|
+
maxAge: 1000 * 60 * 60 * 24, // 24 hours
|
|
820
|
+
})
|
|
821
|
+
```
|
|
1057
822
|
|
|
1058
|
-
|
|
823
|
+
## Best Practices
|
|
824
|
+
|
|
825
|
+
1. **Use `queryOptions` helper** for type-safe, reusable query configurations
|
|
826
|
+
2. **Structure query keys hierarchically** for granular invalidation
|
|
827
|
+
3. **Set appropriate `staleTime`** - 0 means always refetch on mount (default), increase for less dynamic data
|
|
828
|
+
4. **Use `placeholderData`** (not `initialData`) for keeping previous page data during pagination
|
|
829
|
+
5. **Prefer `useSuspenseQuery`** when using Suspense boundaries for cleaner component code
|
|
830
|
+
6. **Use `enabled`** for dependent queries, not conditional hook calls
|
|
831
|
+
7. **Always invalidate after mutations** - don't rely solely on optimistic updates
|
|
832
|
+
8. **Cancel queries in `onMutate`** before optimistic updates to prevent race conditions
|
|
833
|
+
9. **Use `ensureQueryData`** in route loaders instead of `prefetchQuery` for immediate access
|
|
834
|
+
10. **Set `retry: false` in tests** to avoid timeout issues
|
|
835
|
+
11. **Don't destructure the query result** if you need to pass it around (breaks reactivity)
|
|
836
|
+
12. **Use `select`** for derived data instead of transforming in the component
|
|
837
|
+
13. **Keep query functions pure** - they should only fetch, not cause side effects
|
|
838
|
+
14. **Use `gcTime: Infinity`** in tests to prevent cache cleanup during assertions
|
|
839
|
+
|
|
840
|
+
## Common Pitfalls
|
|
841
|
+
|
|
842
|
+
- Using `initialData` when you mean `placeholderData` (initialData counts as "fresh" data)
|
|
843
|
+
- Not providing `initialPageParam` for infinite queries (required in v5)
|
|
844
|
+
- Calling hooks conditionally (violates React rules)
|
|
845
|
+
- Not cancelling queries before optimistic updates (race conditions)
|
|
846
|
+
- Setting `staleTime` higher than `gcTime` (data gets garbage collected while "fresh")
|
|
847
|
+
- Forgetting to wrap tests with `QueryClientProvider`
|
|
848
|
+
- Using same `QueryClient` instance across tests (shared state)
|
|
849
|
+
- Not awaiting `invalidateQueries` in mutation callbacks when order matters
|