@tanstack/react-query 5.102.8 → 5.103.1

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.
Files changed (298) hide show
  1. package/build/legacy/HydrationBoundary.cjs +44 -1
  2. package/build/legacy/HydrationBoundary.cjs.map +1 -1
  3. package/build/legacy/HydrationBoundary.d.cts +61 -0
  4. package/build/legacy/HydrationBoundary.d.cts.map +1 -1
  5. package/build/legacy/HydrationBoundary.d.ts +61 -0
  6. package/build/legacy/HydrationBoundary.d.ts.map +1 -1
  7. package/build/legacy/HydrationBoundary.js +44 -1
  8. package/build/legacy/HydrationBoundary.js.map +1 -1
  9. package/build/legacy/IsRestoringProvider.cjs +11 -0
  10. package/build/legacy/IsRestoringProvider.cjs.map +1 -1
  11. package/build/legacy/IsRestoringProvider.d.cts +11 -0
  12. package/build/legacy/IsRestoringProvider.d.cts.map +1 -1
  13. package/build/legacy/IsRestoringProvider.d.ts +11 -0
  14. package/build/legacy/IsRestoringProvider.d.ts.map +1 -1
  15. package/build/legacy/IsRestoringProvider.js +11 -0
  16. package/build/legacy/IsRestoringProvider.js.map +1 -1
  17. package/build/legacy/QueryClientProvider.cjs +30 -0
  18. package/build/legacy/QueryClientProvider.cjs.map +1 -1
  19. package/build/legacy/QueryClientProvider.d.cts +41 -0
  20. package/build/legacy/QueryClientProvider.d.cts.map +1 -1
  21. package/build/legacy/QueryClientProvider.d.ts +41 -0
  22. package/build/legacy/QueryClientProvider.d.ts.map +1 -1
  23. package/build/legacy/QueryClientProvider.js +30 -0
  24. package/build/legacy/QueryClientProvider.js.map +1 -1
  25. package/build/legacy/QueryErrorResetBoundary.cjs +76 -0
  26. package/build/legacy/QueryErrorResetBoundary.cjs.map +1 -1
  27. package/build/legacy/QueryErrorResetBoundary.d.cts +77 -0
  28. package/build/legacy/QueryErrorResetBoundary.d.cts.map +1 -1
  29. package/build/legacy/QueryErrorResetBoundary.d.ts +77 -0
  30. package/build/legacy/QueryErrorResetBoundary.d.ts.map +1 -1
  31. package/build/legacy/QueryErrorResetBoundary.js +76 -0
  32. package/build/legacy/QueryErrorResetBoundary.js.map +1 -1
  33. package/build/legacy/infiniteQueryOptions.cjs.map +1 -1
  34. package/build/legacy/infiniteQueryOptions.d.cts +173 -0
  35. package/build/legacy/infiniteQueryOptions.d.cts.map +1 -1
  36. package/build/legacy/infiniteQueryOptions.d.ts +173 -0
  37. package/build/legacy/infiniteQueryOptions.d.ts.map +1 -1
  38. package/build/legacy/infiniteQueryOptions.js.map +1 -1
  39. package/build/legacy/mutationOptions.cjs.map +1 -1
  40. package/build/legacy/mutationOptions.d.cts +55 -0
  41. package/build/legacy/mutationOptions.d.cts.map +1 -1
  42. package/build/legacy/mutationOptions.d.ts +55 -0
  43. package/build/legacy/mutationOptions.d.ts.map +1 -1
  44. package/build/legacy/mutationOptions.js.map +1 -1
  45. package/build/legacy/queryOptions.cjs.map +1 -1
  46. package/build/legacy/queryOptions.d.cts +175 -0
  47. package/build/legacy/queryOptions.d.cts.map +1 -1
  48. package/build/legacy/queryOptions.d.ts +175 -0
  49. package/build/legacy/queryOptions.d.ts.map +1 -1
  50. package/build/legacy/queryOptions.js.map +1 -1
  51. package/build/legacy/types.cjs.map +1 -1
  52. package/build/legacy/types.d.cts +228 -2
  53. package/build/legacy/types.d.cts.map +1 -1
  54. package/build/legacy/types.d.ts +228 -2
  55. package/build/legacy/types.d.ts.map +1 -1
  56. package/build/legacy/types.js.map +1 -1
  57. package/build/legacy/useInfiniteQuery.cjs.map +1 -1
  58. package/build/legacy/useInfiniteQuery.d.cts +292 -0
  59. package/build/legacy/useInfiniteQuery.d.cts.map +1 -1
  60. package/build/legacy/useInfiniteQuery.d.ts +292 -0
  61. package/build/legacy/useInfiniteQuery.d.ts.map +1 -1
  62. package/build/legacy/useInfiniteQuery.js.map +1 -1
  63. package/build/legacy/useIsFetching.cjs +36 -0
  64. package/build/legacy/useIsFetching.cjs.map +1 -1
  65. package/build/legacy/useIsFetching.d.cts +36 -0
  66. package/build/legacy/useIsFetching.d.cts.map +1 -1
  67. package/build/legacy/useIsFetching.d.ts +36 -0
  68. package/build/legacy/useIsFetching.d.ts.map +1 -1
  69. package/build/legacy/useIsFetching.js +36 -0
  70. package/build/legacy/useIsFetching.js.map +1 -1
  71. package/build/legacy/useMutation.cjs +172 -0
  72. package/build/legacy/useMutation.cjs.map +1 -1
  73. package/build/legacy/useMutation.d.cts +172 -0
  74. package/build/legacy/useMutation.d.cts.map +1 -1
  75. package/build/legacy/useMutation.d.ts +172 -0
  76. package/build/legacy/useMutation.d.ts.map +1 -1
  77. package/build/legacy/useMutation.js +172 -0
  78. package/build/legacy/useMutation.js.map +1 -1
  79. package/build/legacy/useMutationState.cjs +94 -0
  80. package/build/legacy/useMutationState.cjs.map +1 -1
  81. package/build/legacy/useMutationState.d.cts +94 -0
  82. package/build/legacy/useMutationState.d.cts.map +1 -1
  83. package/build/legacy/useMutationState.d.ts +94 -0
  84. package/build/legacy/useMutationState.d.ts.map +1 -1
  85. package/build/legacy/useMutationState.js +94 -0
  86. package/build/legacy/useMutationState.js.map +1 -1
  87. package/build/legacy/usePrefetchInfiniteQuery.cjs +44 -0
  88. package/build/legacy/usePrefetchInfiniteQuery.cjs.map +1 -1
  89. package/build/legacy/usePrefetchInfiniteQuery.d.cts +44 -0
  90. package/build/legacy/usePrefetchInfiniteQuery.d.cts.map +1 -1
  91. package/build/legacy/usePrefetchInfiniteQuery.d.ts +44 -0
  92. package/build/legacy/usePrefetchInfiniteQuery.d.ts.map +1 -1
  93. package/build/legacy/usePrefetchInfiniteQuery.js +44 -0
  94. package/build/legacy/usePrefetchInfiniteQuery.js.map +1 -1
  95. package/build/legacy/usePrefetchQuery.cjs +35 -0
  96. package/build/legacy/usePrefetchQuery.cjs.map +1 -1
  97. package/build/legacy/usePrefetchQuery.d.cts +35 -0
  98. package/build/legacy/usePrefetchQuery.d.cts.map +1 -1
  99. package/build/legacy/usePrefetchQuery.d.ts +35 -0
  100. package/build/legacy/usePrefetchQuery.d.ts.map +1 -1
  101. package/build/legacy/usePrefetchQuery.js +35 -0
  102. package/build/legacy/usePrefetchQuery.js.map +1 -1
  103. package/build/legacy/useQueries.cjs +130 -0
  104. package/build/legacy/useQueries.cjs.map +1 -1
  105. package/build/legacy/useQueries.d.cts +165 -2
  106. package/build/legacy/useQueries.d.cts.map +1 -1
  107. package/build/legacy/useQueries.d.ts +165 -2
  108. package/build/legacy/useQueries.d.ts.map +1 -1
  109. package/build/legacy/useQueries.js +130 -0
  110. package/build/legacy/useQueries.js.map +1 -1
  111. package/build/legacy/useQuery.cjs.map +1 -1
  112. package/build/legacy/useQuery.d.cts +246 -0
  113. package/build/legacy/useQuery.d.cts.map +1 -1
  114. package/build/legacy/useQuery.d.ts +246 -0
  115. package/build/legacy/useQuery.d.ts.map +1 -1
  116. package/build/legacy/useQuery.js.map +1 -1
  117. package/build/legacy/useSuspenseInfiniteQuery.cjs +86 -0
  118. package/build/legacy/useSuspenseInfiniteQuery.cjs.map +1 -1
  119. package/build/legacy/useSuspenseInfiniteQuery.d.cts +86 -0
  120. package/build/legacy/useSuspenseInfiniteQuery.d.cts.map +1 -1
  121. package/build/legacy/useSuspenseInfiniteQuery.d.ts +86 -0
  122. package/build/legacy/useSuspenseInfiniteQuery.d.ts.map +1 -1
  123. package/build/legacy/useSuspenseInfiniteQuery.js +86 -0
  124. package/build/legacy/useSuspenseInfiniteQuery.js.map +1 -1
  125. package/build/legacy/useSuspenseQueries.cjs.map +1 -1
  126. package/build/legacy/useSuspenseQueries.d.cts +320 -2
  127. package/build/legacy/useSuspenseQueries.d.cts.map +1 -1
  128. package/build/legacy/useSuspenseQueries.d.ts +320 -2
  129. package/build/legacy/useSuspenseQueries.d.ts.map +1 -1
  130. package/build/legacy/useSuspenseQueries.js.map +1 -1
  131. package/build/legacy/useSuspenseQuery.cjs +67 -0
  132. package/build/legacy/useSuspenseQuery.cjs.map +1 -1
  133. package/build/legacy/useSuspenseQuery.d.cts +67 -0
  134. package/build/legacy/useSuspenseQuery.d.cts.map +1 -1
  135. package/build/legacy/useSuspenseQuery.d.ts +67 -0
  136. package/build/legacy/useSuspenseQuery.d.ts.map +1 -1
  137. package/build/legacy/useSuspenseQuery.js +67 -0
  138. package/build/legacy/useSuspenseQuery.js.map +1 -1
  139. package/build/modern/HydrationBoundary.cjs +44 -1
  140. package/build/modern/HydrationBoundary.cjs.map +1 -1
  141. package/build/modern/HydrationBoundary.d.cts +61 -0
  142. package/build/modern/HydrationBoundary.d.cts.map +1 -1
  143. package/build/modern/HydrationBoundary.d.ts +61 -0
  144. package/build/modern/HydrationBoundary.d.ts.map +1 -1
  145. package/build/modern/HydrationBoundary.js +44 -1
  146. package/build/modern/HydrationBoundary.js.map +1 -1
  147. package/build/modern/IsRestoringProvider.cjs +11 -0
  148. package/build/modern/IsRestoringProvider.cjs.map +1 -1
  149. package/build/modern/IsRestoringProvider.d.cts +11 -0
  150. package/build/modern/IsRestoringProvider.d.cts.map +1 -1
  151. package/build/modern/IsRestoringProvider.d.ts +11 -0
  152. package/build/modern/IsRestoringProvider.d.ts.map +1 -1
  153. package/build/modern/IsRestoringProvider.js +11 -0
  154. package/build/modern/IsRestoringProvider.js.map +1 -1
  155. package/build/modern/QueryClientProvider.cjs +30 -0
  156. package/build/modern/QueryClientProvider.cjs.map +1 -1
  157. package/build/modern/QueryClientProvider.d.cts +41 -0
  158. package/build/modern/QueryClientProvider.d.cts.map +1 -1
  159. package/build/modern/QueryClientProvider.d.ts +41 -0
  160. package/build/modern/QueryClientProvider.d.ts.map +1 -1
  161. package/build/modern/QueryClientProvider.js +30 -0
  162. package/build/modern/QueryClientProvider.js.map +1 -1
  163. package/build/modern/QueryErrorResetBoundary.cjs +76 -0
  164. package/build/modern/QueryErrorResetBoundary.cjs.map +1 -1
  165. package/build/modern/QueryErrorResetBoundary.d.cts +77 -0
  166. package/build/modern/QueryErrorResetBoundary.d.cts.map +1 -1
  167. package/build/modern/QueryErrorResetBoundary.d.ts +77 -0
  168. package/build/modern/QueryErrorResetBoundary.d.ts.map +1 -1
  169. package/build/modern/QueryErrorResetBoundary.js +76 -0
  170. package/build/modern/QueryErrorResetBoundary.js.map +1 -1
  171. package/build/modern/infiniteQueryOptions.cjs.map +1 -1
  172. package/build/modern/infiniteQueryOptions.d.cts +173 -0
  173. package/build/modern/infiniteQueryOptions.d.cts.map +1 -1
  174. package/build/modern/infiniteQueryOptions.d.ts +173 -0
  175. package/build/modern/infiniteQueryOptions.d.ts.map +1 -1
  176. package/build/modern/infiniteQueryOptions.js.map +1 -1
  177. package/build/modern/mutationOptions.cjs.map +1 -1
  178. package/build/modern/mutationOptions.d.cts +55 -0
  179. package/build/modern/mutationOptions.d.cts.map +1 -1
  180. package/build/modern/mutationOptions.d.ts +55 -0
  181. package/build/modern/mutationOptions.d.ts.map +1 -1
  182. package/build/modern/mutationOptions.js.map +1 -1
  183. package/build/modern/queryOptions.cjs.map +1 -1
  184. package/build/modern/queryOptions.d.cts +175 -0
  185. package/build/modern/queryOptions.d.cts.map +1 -1
  186. package/build/modern/queryOptions.d.ts +175 -0
  187. package/build/modern/queryOptions.d.ts.map +1 -1
  188. package/build/modern/queryOptions.js.map +1 -1
  189. package/build/modern/types.cjs.map +1 -1
  190. package/build/modern/types.d.cts +228 -2
  191. package/build/modern/types.d.cts.map +1 -1
  192. package/build/modern/types.d.ts +228 -2
  193. package/build/modern/types.d.ts.map +1 -1
  194. package/build/modern/types.js.map +1 -1
  195. package/build/modern/useInfiniteQuery.cjs.map +1 -1
  196. package/build/modern/useInfiniteQuery.d.cts +292 -0
  197. package/build/modern/useInfiniteQuery.d.cts.map +1 -1
  198. package/build/modern/useInfiniteQuery.d.ts +292 -0
  199. package/build/modern/useInfiniteQuery.d.ts.map +1 -1
  200. package/build/modern/useInfiniteQuery.js.map +1 -1
  201. package/build/modern/useIsFetching.cjs +36 -0
  202. package/build/modern/useIsFetching.cjs.map +1 -1
  203. package/build/modern/useIsFetching.d.cts +36 -0
  204. package/build/modern/useIsFetching.d.cts.map +1 -1
  205. package/build/modern/useIsFetching.d.ts +36 -0
  206. package/build/modern/useIsFetching.d.ts.map +1 -1
  207. package/build/modern/useIsFetching.js +36 -0
  208. package/build/modern/useIsFetching.js.map +1 -1
  209. package/build/modern/useMutation.cjs +172 -0
  210. package/build/modern/useMutation.cjs.map +1 -1
  211. package/build/modern/useMutation.d.cts +172 -0
  212. package/build/modern/useMutation.d.cts.map +1 -1
  213. package/build/modern/useMutation.d.ts +172 -0
  214. package/build/modern/useMutation.d.ts.map +1 -1
  215. package/build/modern/useMutation.js +172 -0
  216. package/build/modern/useMutation.js.map +1 -1
  217. package/build/modern/useMutationState.cjs +94 -0
  218. package/build/modern/useMutationState.cjs.map +1 -1
  219. package/build/modern/useMutationState.d.cts +94 -0
  220. package/build/modern/useMutationState.d.cts.map +1 -1
  221. package/build/modern/useMutationState.d.ts +94 -0
  222. package/build/modern/useMutationState.d.ts.map +1 -1
  223. package/build/modern/useMutationState.js +94 -0
  224. package/build/modern/useMutationState.js.map +1 -1
  225. package/build/modern/usePrefetchInfiniteQuery.cjs +44 -0
  226. package/build/modern/usePrefetchInfiniteQuery.cjs.map +1 -1
  227. package/build/modern/usePrefetchInfiniteQuery.d.cts +44 -0
  228. package/build/modern/usePrefetchInfiniteQuery.d.cts.map +1 -1
  229. package/build/modern/usePrefetchInfiniteQuery.d.ts +44 -0
  230. package/build/modern/usePrefetchInfiniteQuery.d.ts.map +1 -1
  231. package/build/modern/usePrefetchInfiniteQuery.js +44 -0
  232. package/build/modern/usePrefetchInfiniteQuery.js.map +1 -1
  233. package/build/modern/usePrefetchQuery.cjs +35 -0
  234. package/build/modern/usePrefetchQuery.cjs.map +1 -1
  235. package/build/modern/usePrefetchQuery.d.cts +35 -0
  236. package/build/modern/usePrefetchQuery.d.cts.map +1 -1
  237. package/build/modern/usePrefetchQuery.d.ts +35 -0
  238. package/build/modern/usePrefetchQuery.d.ts.map +1 -1
  239. package/build/modern/usePrefetchQuery.js +35 -0
  240. package/build/modern/usePrefetchQuery.js.map +1 -1
  241. package/build/modern/useQueries.cjs +130 -0
  242. package/build/modern/useQueries.cjs.map +1 -1
  243. package/build/modern/useQueries.d.cts +165 -2
  244. package/build/modern/useQueries.d.cts.map +1 -1
  245. package/build/modern/useQueries.d.ts +165 -2
  246. package/build/modern/useQueries.d.ts.map +1 -1
  247. package/build/modern/useQueries.js +130 -0
  248. package/build/modern/useQueries.js.map +1 -1
  249. package/build/modern/useQuery.cjs.map +1 -1
  250. package/build/modern/useQuery.d.cts +246 -0
  251. package/build/modern/useQuery.d.cts.map +1 -1
  252. package/build/modern/useQuery.d.ts +246 -0
  253. package/build/modern/useQuery.d.ts.map +1 -1
  254. package/build/modern/useQuery.js.map +1 -1
  255. package/build/modern/useSuspenseInfiniteQuery.cjs +86 -0
  256. package/build/modern/useSuspenseInfiniteQuery.cjs.map +1 -1
  257. package/build/modern/useSuspenseInfiniteQuery.d.cts +86 -0
  258. package/build/modern/useSuspenseInfiniteQuery.d.cts.map +1 -1
  259. package/build/modern/useSuspenseInfiniteQuery.d.ts +86 -0
  260. package/build/modern/useSuspenseInfiniteQuery.d.ts.map +1 -1
  261. package/build/modern/useSuspenseInfiniteQuery.js +86 -0
  262. package/build/modern/useSuspenseInfiniteQuery.js.map +1 -1
  263. package/build/modern/useSuspenseQueries.cjs.map +1 -1
  264. package/build/modern/useSuspenseQueries.d.cts +320 -2
  265. package/build/modern/useSuspenseQueries.d.cts.map +1 -1
  266. package/build/modern/useSuspenseQueries.d.ts +320 -2
  267. package/build/modern/useSuspenseQueries.d.ts.map +1 -1
  268. package/build/modern/useSuspenseQueries.js.map +1 -1
  269. package/build/modern/useSuspenseQuery.cjs +67 -0
  270. package/build/modern/useSuspenseQuery.cjs.map +1 -1
  271. package/build/modern/useSuspenseQuery.d.cts +67 -0
  272. package/build/modern/useSuspenseQuery.d.cts.map +1 -1
  273. package/build/modern/useSuspenseQuery.d.ts +67 -0
  274. package/build/modern/useSuspenseQuery.d.ts.map +1 -1
  275. package/build/modern/useSuspenseQuery.js +67 -0
  276. package/build/modern/useSuspenseQuery.js.map +1 -1
  277. package/build/query-codemods/eslint.config.js +7 -0
  278. package/build/query-codemods/root.eslint.config.js +45 -0
  279. package/package.json +11 -11
  280. package/src/HydrationBoundary.tsx +61 -1
  281. package/src/IsRestoringProvider.ts +12 -0
  282. package/src/QueryClientProvider.tsx +41 -0
  283. package/src/QueryErrorResetBoundary.tsx +89 -0
  284. package/src/infiniteQueryOptions.ts +173 -0
  285. package/src/mutationOptions.ts +55 -0
  286. package/src/queryOptions.ts +175 -0
  287. package/src/types.ts +228 -2
  288. package/src/useInfiniteQuery.ts +292 -0
  289. package/src/useIsFetching.ts +36 -0
  290. package/src/useMutation.ts +172 -0
  291. package/src/useMutationState.ts +94 -0
  292. package/src/usePrefetchInfiniteQuery.tsx +44 -0
  293. package/src/usePrefetchQuery.tsx +35 -0
  294. package/src/useQueries.ts +165 -2
  295. package/src/useQuery.ts +246 -0
  296. package/src/useSuspenseInfiniteQuery.ts +86 -0
  297. package/src/useSuspenseQueries.ts +320 -2
  298. package/src/useSuspenseQuery.ts +67 -0
@@ -3,6 +3,178 @@ import { useQueryClient } from "./QueryClientProvider.js";
3
3
  import * as React from "react";
4
4
  import { MutationObserver, noop, notifyManager, shouldThrowError } from "@tanstack/query-core";
5
5
  //#region src/useMutation.ts
6
+ /**
7
+ * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
8
+ * `useMutation` is the hook for that.
9
+ *
10
+ * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites, or to look
11
+ * the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).
12
+ * @param options - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`.
13
+ * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
14
+ * be used.
15
+ * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
16
+ * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
17
+ * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
18
+ * fire only for the latest call you've made, and only while the component is still mounted — unmounting before
19
+ * the mutation settles removes the subscription and prevents them from firing.
20
+ *
21
+ * @example
22
+ * ```tsx
23
+ * import { useMutation, useQueryClient } from '@tanstack/react-query'
24
+ *
25
+ * function AddTodo() {
26
+ * const queryClient = useQueryClient()
27
+ *
28
+ * const addMutation = useMutation({
29
+ * mutationFn: addTodo,
30
+ * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
31
+ * })
32
+ *
33
+ * return (
34
+ * <button
35
+ * onClick={() =>
36
+ * addMutation.mutate('Item', {
37
+ * onError: (error) => console.error('Failed to add item:', error),
38
+ * })
39
+ * }
40
+ * >
41
+ * Add
42
+ * </button>
43
+ * )
44
+ * }
45
+ * ```
46
+ *
47
+ * @example
48
+ * Rendering the mutation's own state, rather than just firing it off:
49
+ * ```tsx
50
+ * import { useMutation, useQueryClient } from '@tanstack/react-query'
51
+ *
52
+ * function AddTodo() {
53
+ * const queryClient = useQueryClient()
54
+ *
55
+ * const addMutation = useMutation({
56
+ * mutationFn: addTodo,
57
+ * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
58
+ * })
59
+ *
60
+ * return (
61
+ * <div>
62
+ * {addMutation.isPending ? (
63
+ * 'Adding todo...'
64
+ * ) : (
65
+ * <>
66
+ * {addMutation.isError ? (
67
+ * <div>An error occurred: {addMutation.error.message}</div>
68
+ * ) : null}
69
+ * <button onClick={() => addMutation.mutate('Item')}>Add</button>
70
+ * </>
71
+ * )}
72
+ * </div>
73
+ * )
74
+ * }
75
+ * ```
76
+ *
77
+ * @example
78
+ * Optimistic update via `onMutate`, rolling back on `onError`:
79
+ * ```tsx
80
+ * import { useMutation, useQueryClient } from '@tanstack/react-query'
81
+ *
82
+ * function AddTodo() {
83
+ * const queryClient = useQueryClient()
84
+ *
85
+ * const addMutation = useMutation({
86
+ * mutationFn: addTodo,
87
+ * onMutate: async (newTodo) => {
88
+ * await queryClient.cancelQueries({ queryKey: ['todos'] })
89
+ * const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
90
+ *
91
+ * queryClient.setQueryData<Array<string>>(['todos'], (old) => [
92
+ * ...(old ?? []),
93
+ * newTodo,
94
+ * ])
95
+ *
96
+ * // Passed to `onError` as `onMutateResult` if the mutation fails.
97
+ * return { previousTodos }
98
+ * },
99
+ * onError: (_err, _newTodo, onMutateResult) => {
100
+ * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
101
+ * },
102
+ * onSettled: () => {
103
+ * queryClient.invalidateQueries({ queryKey: ['todos'] })
104
+ * },
105
+ * })
106
+ *
107
+ * return (
108
+ * <button onClick={() => addMutation.mutate('Item')}>Add</button>
109
+ * )
110
+ * }
111
+ * ```
112
+ *
113
+ * @example
114
+ * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a
115
+ * promise per call instead, so you can wait for all of them when they succeed:
116
+ * ```tsx
117
+ * import { useMutation, useQueryClient } from '@tanstack/react-query'
118
+ *
119
+ * function AddTodos() {
120
+ * const queryClient = useQueryClient()
121
+ *
122
+ * const addMutation = useMutation({
123
+ * mutationFn: addTodo,
124
+ * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
125
+ * })
126
+ *
127
+ * async function handleAddAll(todos: Array<string>) {
128
+ * try {
129
+ * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
130
+ * } catch (error) {
131
+ * console.error('Failed to add todos:', error)
132
+ * }
133
+ * }
134
+ *
135
+ * return (
136
+ * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
137
+ * Add all
138
+ * </button>
139
+ * )
140
+ * }
141
+ * ```
142
+ *
143
+ * @example
144
+ * If some of the mutations above can fail independently of the others, and you want to know which ones
145
+ * did — rather than losing that information the moment the first one rejects — swap `Promise.all` for
146
+ * `Promise.allSettled`:
147
+ * ```tsx
148
+ * import { useMutation, useQueryClient } from '@tanstack/react-query'
149
+ *
150
+ * function AddTodos() {
151
+ * const queryClient = useQueryClient()
152
+ *
153
+ * const addMutation = useMutation({
154
+ * mutationFn: addTodo,
155
+ * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
156
+ * })
157
+ *
158
+ * async function handleAddAll(todos: Array<string>) {
159
+ * const addResults = await Promise.allSettled(
160
+ * todos.map((todo) => addMutation.mutateAsync(todo)),
161
+ * )
162
+ *
163
+ * addResults.forEach((addResult, index) => {
164
+ * if (addResult.status === 'rejected') {
165
+ * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
166
+ * }
167
+ * })
168
+ * }
169
+ *
170
+ * return (
171
+ * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
172
+ * Add all
173
+ * </button>
174
+ * )
175
+ * }
176
+ * ```
177
+ */
6
178
  function useMutation(options, queryClient) {
7
179
  const client = useQueryClient(queryClient);
8
180
  const [observer] = React.useState(() => new MutationObserver(client, options));
@@ -1 +1 @@
1
- {"version":3,"file":"useMutation.js","names":[],"sources":["../../src/useMutation.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\nimport {\n MutationObserver,\n noop,\n notifyManager,\n shouldThrowError,\n} from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n UseMutateFunction,\n UseMutationOptions,\n UseMutationResult,\n} from './types'\nimport type { DefaultError, QueryClient } from '@tanstack/query-core'\n\n// HOOK\n\nexport function useMutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n queryClient?: QueryClient,\n): UseMutationResult<TData, TError, TVariables, TOnMutateResult> {\n const client = useQueryClient(queryClient)\n\n const [observer] = React.useState(\n () =>\n new MutationObserver<TData, TError, TVariables, TOnMutateResult>(\n client,\n options,\n ),\n )\n\n React.useEffect(() => {\n observer.setOptions(options)\n }, [observer, options])\n\n const result = React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) =>\n observer.subscribe(notifyManager.batchCalls(onStoreChange)),\n [observer],\n ),\n () => observer.getCurrentResult(),\n () => observer.getCurrentResult(),\n )\n\n const mutate = React.useCallback<\n UseMutateFunction<TData, TError, TVariables, TOnMutateResult>\n >(\n (\n ...args: Parameters<\n UseMutateFunction<TData, TError, TVariables, TOnMutateResult>\n >\n ) => {\n observer.mutate(args[0] as TVariables, args[1]).catch(noop)\n },\n [observer],\n )\n\n if (\n result.error &&\n shouldThrowError(observer.options.throwOnError, [result.error])\n ) {\n throw result.error\n }\n\n return { ...result, mutate, mutateAsync: result.mutate }\n}\n"],"mappings":";;;;;AAkBA,SAAgB,YAMd,SACA,aAC+D;CAC/D,MAAM,SAAS,eAAe,WAAW;CAEzC,MAAM,CAAC,YAAY,MAAM,eAErB,IAAI,iBACF,QACA,OACF,CACJ;CAEA,MAAM,gBAAgB;EACpB,SAAS,WAAW,OAAO;CAC7B,GAAG,CAAC,UAAU,OAAO,CAAC;CAEtB,MAAM,SAAS,MAAM,qBACnB,MAAM,aACH,kBACC,SAAS,UAAU,cAAc,WAAW,aAAa,CAAC,GAC5D,CAAC,QAAQ,CACX,SACM,SAAS,iBAAiB,SAC1B,SAAS,iBAAiB,CAClC;CAEA,MAAM,SAAS,MAAM,aAIjB,GAAG,SAGA;EACH,SAAS,OAAO,KAAK,IAAkB,KAAK,EAAE,CAAC,CAAC,MAAM,IAAI;CAC5D,GACA,CAAC,QAAQ,CACX;CAEA,IACE,OAAO,SACP,iBAAiB,SAAS,QAAQ,cAAc,CAAC,OAAO,KAAK,CAAC,GAE9D,MAAM,OAAO;CAGf,OAAO;EAAE,GAAG;EAAQ;EAAQ,aAAa,OAAO;CAAO;AACzD"}
1
+ {"version":3,"file":"useMutation.js","names":[],"sources":["../../src/useMutation.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\nimport {\n MutationObserver,\n noop,\n notifyManager,\n shouldThrowError,\n} from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n UseMutateFunction,\n UseMutationOptions,\n UseMutationResult,\n} from './types'\nimport type { DefaultError, QueryClient } from '@tanstack/query-core'\n\n// HOOK\n\n/**\n * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.\n * `useMutation` is the hook for that.\n *\n * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites, or to look\n * the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).\n * @param options - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second\n * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared\n * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks\n * fire only for the latest call you've made, and only while the component is still mounted — unmounting before\n * the mutation settles removes the subscription and prevents them from firing.\n *\n * @example\n * ```tsx\n * import { useMutation, useQueryClient } from '@tanstack/react-query'\n *\n * function AddTodo() {\n * const queryClient = useQueryClient()\n *\n * const addMutation = useMutation({\n * mutationFn: addTodo,\n * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),\n * })\n *\n * return (\n * <button\n * onClick={() =>\n * addMutation.mutate('Item', {\n * onError: (error) => console.error('Failed to add item:', error),\n * })\n * }\n * >\n * Add\n * </button>\n * )\n * }\n * ```\n *\n * @example\n * Rendering the mutation's own state, rather than just firing it off:\n * ```tsx\n * import { useMutation, useQueryClient } from '@tanstack/react-query'\n *\n * function AddTodo() {\n * const queryClient = useQueryClient()\n *\n * const addMutation = useMutation({\n * mutationFn: addTodo,\n * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),\n * })\n *\n * return (\n * <div>\n * {addMutation.isPending ? (\n * 'Adding todo...'\n * ) : (\n * <>\n * {addMutation.isError ? (\n * <div>An error occurred: {addMutation.error.message}</div>\n * ) : null}\n * <button onClick={() => addMutation.mutate('Item')}>Add</button>\n * </>\n * )}\n * </div>\n * )\n * }\n * ```\n *\n * @example\n * Optimistic update via `onMutate`, rolling back on `onError`:\n * ```tsx\n * import { useMutation, useQueryClient } from '@tanstack/react-query'\n *\n * function AddTodo() {\n * const queryClient = useQueryClient()\n *\n * const addMutation = useMutation({\n * mutationFn: addTodo,\n * onMutate: async (newTodo) => {\n * await queryClient.cancelQueries({ queryKey: ['todos'] })\n * const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])\n *\n * queryClient.setQueryData<Array<string>>(['todos'], (old) => [\n * ...(old ?? []),\n * newTodo,\n * ])\n *\n * // Passed to `onError` as `onMutateResult` if the mutation fails.\n * return { previousTodos }\n * },\n * onError: (_err, _newTodo, onMutateResult) => {\n * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)\n * },\n * onSettled: () => {\n * queryClient.invalidateQueries({ queryKey: ['todos'] })\n * },\n * })\n *\n * return (\n * <button onClick={() => addMutation.mutate('Item')}>Add</button>\n * )\n * }\n * ```\n *\n * @example\n * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a\n * promise per call instead, so you can wait for all of them when they succeed:\n * ```tsx\n * import { useMutation, useQueryClient } from '@tanstack/react-query'\n *\n * function AddTodos() {\n * const queryClient = useQueryClient()\n *\n * const addMutation = useMutation({\n * mutationFn: addTodo,\n * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),\n * })\n *\n * async function handleAddAll(todos: Array<string>) {\n * try {\n * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))\n * } catch (error) {\n * console.error('Failed to add todos:', error)\n * }\n * }\n *\n * return (\n * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>\n * Add all\n * </button>\n * )\n * }\n * ```\n *\n * @example\n * If some of the mutations above can fail independently of the others, and you want to know which ones\n * did — rather than losing that information the moment the first one rejects — swap `Promise.all` for\n * `Promise.allSettled`:\n * ```tsx\n * import { useMutation, useQueryClient } from '@tanstack/react-query'\n *\n * function AddTodos() {\n * const queryClient = useQueryClient()\n *\n * const addMutation = useMutation({\n * mutationFn: addTodo,\n * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),\n * })\n *\n * async function handleAddAll(todos: Array<string>) {\n * const addResults = await Promise.allSettled(\n * todos.map((todo) => addMutation.mutateAsync(todo)),\n * )\n *\n * addResults.forEach((addResult, index) => {\n * if (addResult.status === 'rejected') {\n * console.error(`Failed to add \"${todos[index]}\":`, addResult.reason)\n * }\n * })\n * }\n *\n * return (\n * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>\n * Add all\n * </button>\n * )\n * }\n * ```\n */\nexport function useMutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n queryClient?: QueryClient,\n): UseMutationResult<TData, TError, TVariables, TOnMutateResult> {\n const client = useQueryClient(queryClient)\n\n const [observer] = React.useState(\n () =>\n new MutationObserver<TData, TError, TVariables, TOnMutateResult>(\n client,\n options,\n ),\n )\n\n React.useEffect(() => {\n observer.setOptions(options)\n }, [observer, options])\n\n const result = React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) =>\n observer.subscribe(notifyManager.batchCalls(onStoreChange)),\n [observer],\n ),\n () => observer.getCurrentResult(),\n () => observer.getCurrentResult(),\n )\n\n const mutate = React.useCallback<\n UseMutateFunction<TData, TError, TVariables, TOnMutateResult>\n >(\n (\n ...args: Parameters<\n UseMutateFunction<TData, TError, TVariables, TOnMutateResult>\n >\n ) => {\n observer.mutate(args[0] as TVariables, args[1]).catch(noop)\n },\n [observer],\n )\n\n if (\n result.error &&\n shouldThrowError(observer.options.throwOnError, [result.error])\n ) {\n throw result.error\n }\n\n return { ...result, mutate, mutateAsync: result.mutate }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8LA,SAAgB,YAMd,SACA,aAC+D;CAC/D,MAAM,SAAS,eAAe,WAAW;CAEzC,MAAM,CAAC,YAAY,MAAM,eAErB,IAAI,iBACF,QACA,OACF,CACJ;CAEA,MAAM,gBAAgB;EACpB,SAAS,WAAW,OAAO;CAC7B,GAAG,CAAC,UAAU,OAAO,CAAC;CAEtB,MAAM,SAAS,MAAM,qBACnB,MAAM,aACH,kBACC,SAAS,UAAU,cAAc,WAAW,aAAa,CAAC,GAC5D,CAAC,QAAQ,CACX,SACM,SAAS,iBAAiB,SAC1B,SAAS,iBAAiB,CAClC;CAEA,MAAM,SAAS,MAAM,aAIjB,GAAG,SAGA;EACH,SAAS,OAAO,KAAK,IAAkB,KAAK,EAAE,CAAC,CAAC,MAAM,IAAI;CAC5D,GACA,CAAC,QAAQ,CACX;CAEA,IACE,OAAO,SACP,iBAAiB,SAAS,QAAQ,cAAc,CAAC,OAAO,KAAK,CAAC,GAE9D,MAAM,OAAO;CAGf,OAAO;EAAE,GAAG;EAAQ;EAAQ,aAAa,OAAO;CAAO;AACzD"}
@@ -6,6 +6,27 @@ let react = require("react");
6
6
  react = require_rolldown_runtime.__toESM(react, 1);
7
7
  let _tanstack_query_core = require("@tanstack/query-core");
8
8
  //#region src/useMutationState.ts
9
+ /**
10
+ * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`
11
+ * (useful for app-wide loading indicators).
12
+ *
13
+ * @param filters - The {@link MutationFilters} to narrow down the matched mutations.
14
+ * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
15
+ * be used.
16
+ * @returns Will be the `number` of the mutations that your application currently has `pending`.
17
+ *
18
+ * @example
19
+ * ```tsx
20
+ * import { useIsMutating } from '@tanstack/react-query'
21
+ *
22
+ * function PostsMutatingIndicator() {
23
+ * // How many mutations matching the posts prefix are in progress?
24
+ * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
25
+ *
26
+ * return isMutatingPosts ? <span>Saving posts...</span> : null
27
+ * }
28
+ * ```
29
+ */
9
30
  function useIsMutating(filters, queryClient) {
10
31
  const client = require_QueryClientProvider.useQueryClient(queryClient);
11
32
  return useMutationState({ filters: {
@@ -16,6 +37,79 @@ function useIsMutating(filters, queryClient) {
16
37
  function getResult(mutationCache, options) {
17
38
  return mutationCache.findAll(options.filters).map((mutation) => options.select ? options.select(mutation) : mutation.state);
18
39
  }
40
+ /**
41
+ * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass
42
+ * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation
43
+ * state.
44
+ *
45
+ * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the
46
+ * mutation state.
47
+ * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
48
+ * be used.
49
+ * @returns Will be an Array of whatever `select` returns for each matching mutation.
50
+ *
51
+ * @example
52
+ * Get all variables of all running mutations:
53
+ * ```tsx
54
+ * import { useMutationState } from '@tanstack/react-query'
55
+ *
56
+ * function PendingPosts() {
57
+ * const pendingVariables = useMutationState({
58
+ * filters: { status: 'pending' },
59
+ * select: (mutation) => mutation.state.variables,
60
+ * })
61
+ *
62
+ * return <>{pendingVariables.length} posts saving...</>
63
+ * }
64
+ * ```
65
+ *
66
+ * @example
67
+ * Get all data for specific mutations via the `mutationKey`:
68
+ * ```tsx
69
+ * import { useMutation, useMutationState } from '@tanstack/react-query'
70
+ *
71
+ * const mutationKey = ['posts']
72
+ *
73
+ * function Posts() {
74
+ * // Some mutation that we want to get the state for
75
+ * const mutation = useMutation({
76
+ * mutationKey,
77
+ * mutationFn: createPosts,
78
+ * })
79
+ *
80
+ * const savedPosts = useMutationState({
81
+ * // this mutation key needs to match the mutation key of the given mutation (see above)
82
+ * filters: { mutationKey, status: 'success' },
83
+ * select: (mutation) => mutation.state.data,
84
+ * })
85
+ *
86
+ * return (
87
+ * <button onClick={() => mutation.mutate(['New Post'])}>
88
+ * Create post ({savedPosts.length} saved so far)
89
+ * </button>
90
+ * )
91
+ * }
92
+ * ```
93
+ *
94
+ * @example
95
+ * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
96
+ * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the
97
+ * last item that `useMutationState` returns to get the latest successful invocation:
98
+ * ```tsx
99
+ * import { useMutationState } from '@tanstack/react-query'
100
+ *
101
+ * function LatestPost() {
102
+ * const savedPosts = useMutationState({
103
+ * filters: { mutationKey: ['posts'], status: 'success' },
104
+ * select: (mutation) => mutation.state.data,
105
+ * })
106
+ *
107
+ * const latestSavedPost = savedPosts[savedPosts.length - 1]
108
+ *
109
+ * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>
110
+ * }
111
+ * ```
112
+ */
19
113
  function useMutationState(options = {}, queryClient) {
20
114
  const mutationCache = require_QueryClientProvider.useQueryClient(queryClient).getMutationCache();
21
115
  const optionsRef = react.useRef(options);
@@ -1 +1 @@
1
- {"version":3,"file":"useMutationState.cjs","names":["useQueryClient","React","replaceEqualDeep"],"sources":["../../src/useMutationState.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nimport { notifyManager, replaceEqualDeep } from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n QueryClient,\n} from '@tanstack/query-core'\n\nexport function useIsMutating(\n filters?: MutationFilters,\n queryClient?: QueryClient,\n): number {\n const client = useQueryClient(queryClient)\n return useMutationState(\n { filters: { ...filters, status: 'pending' } },\n client,\n ).length\n}\n\ntype MutationTypeFromResult<TResult> = [TResult] extends [\n MutationState<\n infer TData,\n infer TError,\n infer TVariables,\n infer TOnMutateResult\n >,\n]\n ? Mutation<TData, TError, TVariables, TOnMutateResult>\n : Mutation\n\ntype MutationStateOptions<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n> = {\n filters?: MutationFilters\n select?: (mutation: TMutation) => TResult\n}\n\nfunction getResult<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n mutationCache: MutationCache,\n options: MutationStateOptions<TResult, TMutation>,\n): Array<TResult> {\n return mutationCache\n .findAll(options.filters)\n .map(\n (mutation): TResult =>\n (options.select\n ? options.select(mutation as TMutation)\n : mutation.state) as TResult,\n )\n}\n\nexport function useMutationState<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n options: MutationStateOptions<TResult, TMutation> = {},\n queryClient?: QueryClient,\n): Array<TResult> {\n const mutationCache = useQueryClient(queryClient).getMutationCache()\n const optionsRef = React.useRef(options)\n const result = React.useRef<Array<TResult>>(null)\n if (result.current === null) {\n result.current = getResult(mutationCache, options)\n }\n\n React.useEffect(() => {\n optionsRef.current = options\n })\n\n return React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) =>\n mutationCache.subscribe(() => {\n const nextResult = replaceEqualDeep(\n result.current,\n getResult(mutationCache, optionsRef.current),\n )\n if (result.current !== nextResult) {\n result.current = nextResult\n notifyManager.schedule(onStoreChange)\n }\n }),\n [mutationCache],\n ),\n () => result.current,\n () => result.current,\n )!\n}\n"],"mappings":";;;;;;;;AAaA,SAAgB,cACd,SACA,aACQ;CACR,MAAM,SAASA,4BAAAA,eAAe,WAAW;CACzC,OAAO,iBACL,EAAE,SAAS;EAAE,GAAG;EAAS,QAAQ;CAAU,EAAE,GAC7C,MACF,CAAC,CAAC;AACJ;AAsBA,SAAS,UAKP,eACA,SACgB;CAChB,OAAO,cACJ,QAAQ,QAAQ,OAAO,CAAC,CACxB,KACE,aACE,QAAQ,SACL,QAAQ,OAAO,QAAqB,IACpC,SAAS,KACjB;AACJ;AAEA,SAAgB,iBAKd,UAAoD,CAAC,GACrD,aACgB;CAChB,MAAM,gBAAgBA,4BAAAA,eAAe,WAAW,CAAC,CAAC,iBAAiB;CACnE,MAAM,aAAaC,MAAM,OAAO,OAAO;CACvC,MAAM,SAASA,MAAM,OAAuB,IAAI;CAChD,IAAI,OAAO,YAAY,MACrB,OAAO,UAAU,UAAU,eAAe,OAAO;CAGnD,MAAM,gBAAgB;EACpB,WAAW,UAAU;CACvB,CAAC;CAED,OAAOA,MAAM,qBACXA,MAAM,aACH,kBACC,cAAc,gBAAgB;EAC5B,MAAM,cAAA,GAAaC,qBAAAA,iBAAAA,CACjB,OAAO,SACP,UAAU,eAAe,WAAW,OAAO,CAC7C;EACA,IAAI,OAAO,YAAY,YAAY;GACjC,OAAO,UAAU;GACjB,qBAAA,cAAc,SAAS,aAAa;EACtC;CACF,CAAC,GACH,CAAC,aAAa,CAChB,SACM,OAAO,eACP,OAAO,OACf;AACF"}
1
+ {"version":3,"file":"useMutationState.cjs","names":["useQueryClient","React","replaceEqualDeep"],"sources":["../../src/useMutationState.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nimport { notifyManager, replaceEqualDeep } from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`\n * (useful for app-wide loading indicators).\n *\n * @param filters - The {@link MutationFilters} to narrow down the matched mutations.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be the `number` of the mutations that your application currently has `pending`.\n *\n * @example\n * ```tsx\n * import { useIsMutating } from '@tanstack/react-query'\n *\n * function PostsMutatingIndicator() {\n * // How many mutations matching the posts prefix are in progress?\n * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })\n *\n * return isMutatingPosts ? <span>Saving posts...</span> : null\n * }\n * ```\n */\nexport function useIsMutating(\n filters?: MutationFilters,\n queryClient?: QueryClient,\n): number {\n const client = useQueryClient(queryClient)\n return useMutationState(\n { filters: { ...filters, status: 'pending' } },\n client,\n ).length\n}\n\ntype MutationTypeFromResult<TResult> = [TResult] extends [\n MutationState<\n infer TData,\n infer TError,\n infer TVariables,\n infer TOnMutateResult\n >,\n]\n ? Mutation<TData, TError, TVariables, TOnMutateResult>\n : Mutation\n\ntype MutationStateOptions<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n> = {\n filters?: MutationFilters\n select?: (mutation: TMutation) => TResult\n}\n\nfunction getResult<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n mutationCache: MutationCache,\n options: MutationStateOptions<TResult, TMutation>,\n): Array<TResult> {\n return mutationCache\n .findAll(options.filters)\n .map(\n (mutation): TResult =>\n (options.select\n ? options.select(mutation as TMutation)\n : mutation.state) as TResult,\n )\n}\n\n/**\n * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass\n * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation\n * state.\n *\n * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the\n * mutation state.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be an Array of whatever `select` returns for each matching mutation.\n *\n * @example\n * Get all variables of all running mutations:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function PendingPosts() {\n * const pendingVariables = useMutationState({\n * filters: { status: 'pending' },\n * select: (mutation) => mutation.state.variables,\n * })\n *\n * return <>{pendingVariables.length} posts saving...</>\n * }\n * ```\n *\n * @example\n * Get all data for specific mutations via the `mutationKey`:\n * ```tsx\n * import { useMutation, useMutationState } from '@tanstack/react-query'\n *\n * const mutationKey = ['posts']\n *\n * function Posts() {\n * // Some mutation that we want to get the state for\n * const mutation = useMutation({\n * mutationKey,\n * mutationFn: createPosts,\n * })\n *\n * const savedPosts = useMutationState({\n * // this mutation key needs to match the mutation key of the given mutation (see above)\n * filters: { mutationKey, status: 'success' },\n * select: (mutation) => mutation.state.data,\n * })\n *\n * return (\n * <button onClick={() => mutation.mutate(['New Post'])}>\n * Create post ({savedPosts.length} saved so far)\n * </button>\n * )\n * }\n * ```\n *\n * @example\n * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new\n * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the\n * last item that `useMutationState` returns to get the latest successful invocation:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function LatestPost() {\n * const savedPosts = useMutationState({\n * filters: { mutationKey: ['posts'], status: 'success' },\n * select: (mutation) => mutation.state.data,\n * })\n *\n * const latestSavedPost = savedPosts[savedPosts.length - 1]\n *\n * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>\n * }\n * ```\n */\nexport function useMutationState<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n options: MutationStateOptions<TResult, TMutation> = {},\n queryClient?: QueryClient,\n): Array<TResult> {\n const mutationCache = useQueryClient(queryClient).getMutationCache()\n const optionsRef = React.useRef(options)\n const result = React.useRef<Array<TResult>>(null)\n if (result.current === null) {\n result.current = getResult(mutationCache, options)\n }\n\n React.useEffect(() => {\n optionsRef.current = options\n })\n\n return React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) =>\n mutationCache.subscribe(() => {\n const nextResult = replaceEqualDeep(\n result.current,\n getResult(mutationCache, optionsRef.current),\n )\n if (result.current !== nextResult) {\n result.current = nextResult\n notifyManager.schedule(onStoreChange)\n }\n }),\n [mutationCache],\n ),\n () => result.current,\n () => result.current,\n )!\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,cACd,SACA,aACQ;CACR,MAAM,SAASA,4BAAAA,eAAe,WAAW;CACzC,OAAO,iBACL,EAAE,SAAS;EAAE,GAAG;EAAS,QAAQ;CAAU,EAAE,GAC7C,MACF,CAAC,CAAC;AACJ;AAsBA,SAAS,UAKP,eACA,SACgB;CAChB,OAAO,cACJ,QAAQ,QAAQ,OAAO,CAAC,CACxB,KACE,aACE,QAAQ,SACL,QAAQ,OAAO,QAAqB,IACpC,SAAS,KACjB;AACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2EA,SAAgB,iBAKd,UAAoD,CAAC,GACrD,aACgB;CAChB,MAAM,gBAAgBA,4BAAAA,eAAe,WAAW,CAAC,CAAC,iBAAiB;CACnE,MAAM,aAAaC,MAAM,OAAO,OAAO;CACvC,MAAM,SAASA,MAAM,OAAuB,IAAI;CAChD,IAAI,OAAO,YAAY,MACrB,OAAO,UAAU,UAAU,eAAe,OAAO;CAGnD,MAAM,gBAAgB;EACpB,WAAW,UAAU;CACvB,CAAC;CAED,OAAOA,MAAM,qBACXA,MAAM,aACH,kBACC,cAAc,gBAAgB;EAC5B,MAAM,cAAA,GAAaC,qBAAAA,iBAAAA,CACjB,OAAO,SACP,UAAU,eAAe,WAAW,OAAO,CAC7C;EACA,IAAI,OAAO,YAAY,YAAY;GACjC,OAAO,UAAU;GACjB,qBAAA,cAAc,SAAS,aAAa;EACtC;CACF,CAAC,GACH,CAAC,aAAa,CAChB,SACM,OAAO,eACP,OAAO,OACf;AACF"}
@@ -1,11 +1,105 @@
1
1
  import { Mutation, MutationFilters, MutationState, QueryClient } from "@tanstack/query-core";
2
2
  //#region src/useMutationState.d.ts
3
+ /**
4
+ * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`
5
+ * (useful for app-wide loading indicators).
6
+ *
7
+ * @param filters - The {@link MutationFilters} to narrow down the matched mutations.
8
+ * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
9
+ * be used.
10
+ * @returns Will be the `number` of the mutations that your application currently has `pending`.
11
+ *
12
+ * @example
13
+ * ```tsx
14
+ * import { useIsMutating } from '@tanstack/react-query'
15
+ *
16
+ * function PostsMutatingIndicator() {
17
+ * // How many mutations matching the posts prefix are in progress?
18
+ * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
19
+ *
20
+ * return isMutatingPosts ? <span>Saving posts...</span> : null
21
+ * }
22
+ * ```
23
+ */
3
24
  declare function useIsMutating(filters?: MutationFilters, queryClient?: QueryClient): number;
4
25
  type MutationTypeFromResult<TResult> = [TResult] extends [MutationState<infer TData, infer TError, infer TVariables, infer TOnMutateResult>] ? Mutation<TData, TError, TVariables, TOnMutateResult> : Mutation;
5
26
  type MutationStateOptions<TResult = MutationState, TMutation extends Mutation<any, any, any, any> = MutationTypeFromResult<TResult>> = {
6
27
  filters?: MutationFilters;
7
28
  select?: (mutation: TMutation) => TResult;
8
29
  };
30
+ /**
31
+ * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass
32
+ * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation
33
+ * state.
34
+ *
35
+ * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the
36
+ * mutation state.
37
+ * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
38
+ * be used.
39
+ * @returns Will be an Array of whatever `select` returns for each matching mutation.
40
+ *
41
+ * @example
42
+ * Get all variables of all running mutations:
43
+ * ```tsx
44
+ * import { useMutationState } from '@tanstack/react-query'
45
+ *
46
+ * function PendingPosts() {
47
+ * const pendingVariables = useMutationState({
48
+ * filters: { status: 'pending' },
49
+ * select: (mutation) => mutation.state.variables,
50
+ * })
51
+ *
52
+ * return <>{pendingVariables.length} posts saving...</>
53
+ * }
54
+ * ```
55
+ *
56
+ * @example
57
+ * Get all data for specific mutations via the `mutationKey`:
58
+ * ```tsx
59
+ * import { useMutation, useMutationState } from '@tanstack/react-query'
60
+ *
61
+ * const mutationKey = ['posts']
62
+ *
63
+ * function Posts() {
64
+ * // Some mutation that we want to get the state for
65
+ * const mutation = useMutation({
66
+ * mutationKey,
67
+ * mutationFn: createPosts,
68
+ * })
69
+ *
70
+ * const savedPosts = useMutationState({
71
+ * // this mutation key needs to match the mutation key of the given mutation (see above)
72
+ * filters: { mutationKey, status: 'success' },
73
+ * select: (mutation) => mutation.state.data,
74
+ * })
75
+ *
76
+ * return (
77
+ * <button onClick={() => mutation.mutate(['New Post'])}>
78
+ * Create post ({savedPosts.length} saved so far)
79
+ * </button>
80
+ * )
81
+ * }
82
+ * ```
83
+ *
84
+ * @example
85
+ * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
86
+ * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the
87
+ * last item that `useMutationState` returns to get the latest successful invocation:
88
+ * ```tsx
89
+ * import { useMutationState } from '@tanstack/react-query'
90
+ *
91
+ * function LatestPost() {
92
+ * const savedPosts = useMutationState({
93
+ * filters: { mutationKey: ['posts'], status: 'success' },
94
+ * select: (mutation) => mutation.state.data,
95
+ * })
96
+ *
97
+ * const latestSavedPost = savedPosts[savedPosts.length - 1]
98
+ *
99
+ * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>
100
+ * }
101
+ * ```
102
+ */
9
103
  declare function useMutationState<TResult = MutationState, TMutation extends Mutation<any, any, any, any> = MutationTypeFromResult<TResult>>(options?: MutationStateOptions<TResult, TMutation>, queryClient?: QueryClient): Array<TResult>;
10
104
  //#endregion
11
105
  export { useIsMutating, useMutationState };
@@ -1 +1 @@
1
- {"version":3,"file":"useMutationState.d.cts","names":[],"sources":["../../src/useMutationState.ts"],"mappings":";;iBAagB,cACd,UAAU,iBACV,cAAc;KASX,uBAAuB,YAAY,kBACtC,oBACQ,aACA,cACA,kBACA,oBAGN,SAAS,OAAO,QAAQ,YAAY,mBACpC;KAEC,qBACH,UAAU,eACV,kBAAkB,+BAChB,uBAAuB;EAEzB,UAAU;EACV,UAAU,UAAU,cAAc;;iBAqBpB,iBACd,UAAU,eACV,kBAAkB,+BAChB,uBAAuB,UAEzB,UAAS,qBAAqB,SAAS,YACvC,cAAc,cACb,MAAM"}
1
+ {"version":3,"file":"useMutationState.d.cts","names":[],"sources":["../../src/useMutationState.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;iBAkCgB,cACd,UAAU,iBACV,cAAc;KASX,uBAAuB,YAAY,kBACtC,oBACQ,aACA,cACA,kBACA,oBAGN,SAAS,OAAO,QAAQ,YAAY,mBACpC;KAEC,qBACH,UAAU,eACV,kBAAkB,+BAChB,uBAAuB;EAEzB,UAAU;EACV,UAAU,UAAU,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8FpB,iBACd,UAAU,eACV,kBAAkB,+BAChB,uBAAuB,UAEzB,UAAS,qBAAqB,SAAS,YACvC,cAAc,cACb,MAAM"}
@@ -1,11 +1,105 @@
1
1
  import { Mutation, MutationFilters, MutationState, QueryClient } from "@tanstack/query-core";
2
2
  //#region src/useMutationState.d.ts
3
+ /**
4
+ * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`
5
+ * (useful for app-wide loading indicators).
6
+ *
7
+ * @param filters - The {@link MutationFilters} to narrow down the matched mutations.
8
+ * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
9
+ * be used.
10
+ * @returns Will be the `number` of the mutations that your application currently has `pending`.
11
+ *
12
+ * @example
13
+ * ```tsx
14
+ * import { useIsMutating } from '@tanstack/react-query'
15
+ *
16
+ * function PostsMutatingIndicator() {
17
+ * // How many mutations matching the posts prefix are in progress?
18
+ * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
19
+ *
20
+ * return isMutatingPosts ? <span>Saving posts...</span> : null
21
+ * }
22
+ * ```
23
+ */
3
24
  declare function useIsMutating(filters?: MutationFilters, queryClient?: QueryClient): number;
4
25
  type MutationTypeFromResult<TResult> = [TResult] extends [MutationState<infer TData, infer TError, infer TVariables, infer TOnMutateResult>] ? Mutation<TData, TError, TVariables, TOnMutateResult> : Mutation;
5
26
  type MutationStateOptions<TResult = MutationState, TMutation extends Mutation<any, any, any, any> = MutationTypeFromResult<TResult>> = {
6
27
  filters?: MutationFilters;
7
28
  select?: (mutation: TMutation) => TResult;
8
29
  };
30
+ /**
31
+ * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass
32
+ * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation
33
+ * state.
34
+ *
35
+ * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the
36
+ * mutation state.
37
+ * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
38
+ * be used.
39
+ * @returns Will be an Array of whatever `select` returns for each matching mutation.
40
+ *
41
+ * @example
42
+ * Get all variables of all running mutations:
43
+ * ```tsx
44
+ * import { useMutationState } from '@tanstack/react-query'
45
+ *
46
+ * function PendingPosts() {
47
+ * const pendingVariables = useMutationState({
48
+ * filters: { status: 'pending' },
49
+ * select: (mutation) => mutation.state.variables,
50
+ * })
51
+ *
52
+ * return <>{pendingVariables.length} posts saving...</>
53
+ * }
54
+ * ```
55
+ *
56
+ * @example
57
+ * Get all data for specific mutations via the `mutationKey`:
58
+ * ```tsx
59
+ * import { useMutation, useMutationState } from '@tanstack/react-query'
60
+ *
61
+ * const mutationKey = ['posts']
62
+ *
63
+ * function Posts() {
64
+ * // Some mutation that we want to get the state for
65
+ * const mutation = useMutation({
66
+ * mutationKey,
67
+ * mutationFn: createPosts,
68
+ * })
69
+ *
70
+ * const savedPosts = useMutationState({
71
+ * // this mutation key needs to match the mutation key of the given mutation (see above)
72
+ * filters: { mutationKey, status: 'success' },
73
+ * select: (mutation) => mutation.state.data,
74
+ * })
75
+ *
76
+ * return (
77
+ * <button onClick={() => mutation.mutate(['New Post'])}>
78
+ * Create post ({savedPosts.length} saved so far)
79
+ * </button>
80
+ * )
81
+ * }
82
+ * ```
83
+ *
84
+ * @example
85
+ * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
86
+ * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the
87
+ * last item that `useMutationState` returns to get the latest successful invocation:
88
+ * ```tsx
89
+ * import { useMutationState } from '@tanstack/react-query'
90
+ *
91
+ * function LatestPost() {
92
+ * const savedPosts = useMutationState({
93
+ * filters: { mutationKey: ['posts'], status: 'success' },
94
+ * select: (mutation) => mutation.state.data,
95
+ * })
96
+ *
97
+ * const latestSavedPost = savedPosts[savedPosts.length - 1]
98
+ *
99
+ * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>
100
+ * }
101
+ * ```
102
+ */
9
103
  declare function useMutationState<TResult = MutationState, TMutation extends Mutation<any, any, any, any> = MutationTypeFromResult<TResult>>(options?: MutationStateOptions<TResult, TMutation>, queryClient?: QueryClient): Array<TResult>;
10
104
  //#endregion
11
105
  export { useIsMutating, useMutationState };
@@ -1 +1 @@
1
- {"version":3,"file":"useMutationState.d.ts","names":[],"sources":["../../src/useMutationState.ts"],"mappings":";;iBAagB,cACd,UAAU,iBACV,cAAc;KASX,uBAAuB,YAAY,kBACtC,oBACQ,aACA,cACA,kBACA,oBAGN,SAAS,OAAO,QAAQ,YAAY,mBACpC;KAEC,qBACH,UAAU,eACV,kBAAkB,+BAChB,uBAAuB;EAEzB,UAAU;EACV,UAAU,UAAU,cAAc;;iBAqBpB,iBACd,UAAU,eACV,kBAAkB,+BAChB,uBAAuB,UAEzB,UAAS,qBAAqB,SAAS,YACvC,cAAc,cACb,MAAM"}
1
+ {"version":3,"file":"useMutationState.d.ts","names":[],"sources":["../../src/useMutationState.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;iBAkCgB,cACd,UAAU,iBACV,cAAc;KASX,uBAAuB,YAAY,kBACtC,oBACQ,aACA,cACA,kBACA,oBAGN,SAAS,OAAO,QAAQ,YAAY,mBACpC;KAEC,qBACH,UAAU,eACV,kBAAkB,+BAChB,uBAAuB;EAEzB,UAAU;EACV,UAAU,UAAU,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8FpB,iBACd,UAAU,eACV,kBAAkB,+BAChB,uBAAuB,UAEzB,UAAS,qBAAqB,SAAS,YACvC,cAAc,cACb,MAAM"}
@@ -3,6 +3,27 @@ import { useQueryClient } from "./QueryClientProvider.js";
3
3
  import * as React from "react";
4
4
  import { notifyManager, replaceEqualDeep } from "@tanstack/query-core";
5
5
  //#region src/useMutationState.ts
6
+ /**
7
+ * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`
8
+ * (useful for app-wide loading indicators).
9
+ *
10
+ * @param filters - The {@link MutationFilters} to narrow down the matched mutations.
11
+ * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
12
+ * be used.
13
+ * @returns Will be the `number` of the mutations that your application currently has `pending`.
14
+ *
15
+ * @example
16
+ * ```tsx
17
+ * import { useIsMutating } from '@tanstack/react-query'
18
+ *
19
+ * function PostsMutatingIndicator() {
20
+ * // How many mutations matching the posts prefix are in progress?
21
+ * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
22
+ *
23
+ * return isMutatingPosts ? <span>Saving posts...</span> : null
24
+ * }
25
+ * ```
26
+ */
6
27
  function useIsMutating(filters, queryClient) {
7
28
  const client = useQueryClient(queryClient);
8
29
  return useMutationState({ filters: {
@@ -13,6 +34,79 @@ function useIsMutating(filters, queryClient) {
13
34
  function getResult(mutationCache, options) {
14
35
  return mutationCache.findAll(options.filters).map((mutation) => options.select ? options.select(mutation) : mutation.state);
15
36
  }
37
+ /**
38
+ * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass
39
+ * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation
40
+ * state.
41
+ *
42
+ * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the
43
+ * mutation state.
44
+ * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
45
+ * be used.
46
+ * @returns Will be an Array of whatever `select` returns for each matching mutation.
47
+ *
48
+ * @example
49
+ * Get all variables of all running mutations:
50
+ * ```tsx
51
+ * import { useMutationState } from '@tanstack/react-query'
52
+ *
53
+ * function PendingPosts() {
54
+ * const pendingVariables = useMutationState({
55
+ * filters: { status: 'pending' },
56
+ * select: (mutation) => mutation.state.variables,
57
+ * })
58
+ *
59
+ * return <>{pendingVariables.length} posts saving...</>
60
+ * }
61
+ * ```
62
+ *
63
+ * @example
64
+ * Get all data for specific mutations via the `mutationKey`:
65
+ * ```tsx
66
+ * import { useMutation, useMutationState } from '@tanstack/react-query'
67
+ *
68
+ * const mutationKey = ['posts']
69
+ *
70
+ * function Posts() {
71
+ * // Some mutation that we want to get the state for
72
+ * const mutation = useMutation({
73
+ * mutationKey,
74
+ * mutationFn: createPosts,
75
+ * })
76
+ *
77
+ * const savedPosts = useMutationState({
78
+ * // this mutation key needs to match the mutation key of the given mutation (see above)
79
+ * filters: { mutationKey, status: 'success' },
80
+ * select: (mutation) => mutation.state.data,
81
+ * })
82
+ *
83
+ * return (
84
+ * <button onClick={() => mutation.mutate(['New Post'])}>
85
+ * Create post ({savedPosts.length} saved so far)
86
+ * </button>
87
+ * )
88
+ * }
89
+ * ```
90
+ *
91
+ * @example
92
+ * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
93
+ * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the
94
+ * last item that `useMutationState` returns to get the latest successful invocation:
95
+ * ```tsx
96
+ * import { useMutationState } from '@tanstack/react-query'
97
+ *
98
+ * function LatestPost() {
99
+ * const savedPosts = useMutationState({
100
+ * filters: { mutationKey: ['posts'], status: 'success' },
101
+ * select: (mutation) => mutation.state.data,
102
+ * })
103
+ *
104
+ * const latestSavedPost = savedPosts[savedPosts.length - 1]
105
+ *
106
+ * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>
107
+ * }
108
+ * ```
109
+ */
16
110
  function useMutationState(options = {}, queryClient) {
17
111
  const mutationCache = useQueryClient(queryClient).getMutationCache();
18
112
  const optionsRef = React.useRef(options);