@tanstack/preact-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 (205) hide show
  1. package/build/legacy/HydrationBoundary.cjs +1 -1
  2. package/build/legacy/HydrationBoundary.cjs.map +1 -1
  3. package/build/legacy/HydrationBoundary.js +1 -1
  4. package/build/legacy/HydrationBoundary.js.map +1 -1
  5. package/build/legacy/QueryErrorResetBoundary.cjs +12 -12
  6. package/build/legacy/QueryErrorResetBoundary.cjs.map +1 -1
  7. package/build/legacy/QueryErrorResetBoundary.d.cts +12 -12
  8. package/build/legacy/QueryErrorResetBoundary.d.ts +12 -12
  9. package/build/legacy/QueryErrorResetBoundary.js +12 -12
  10. package/build/legacy/QueryErrorResetBoundary.js.map +1 -1
  11. package/build/legacy/infiniteQueryOptions.cjs.map +1 -1
  12. package/build/legacy/infiniteQueryOptions.d.cts +41 -55
  13. package/build/legacy/infiniteQueryOptions.d.cts.map +1 -1
  14. package/build/legacy/infiniteQueryOptions.d.ts +41 -55
  15. package/build/legacy/infiniteQueryOptions.d.ts.map +1 -1
  16. package/build/legacy/infiniteQueryOptions.js.map +1 -1
  17. package/build/legacy/mutationOptions.cjs.map +1 -1
  18. package/build/legacy/mutationOptions.d.cts +4 -17
  19. package/build/legacy/mutationOptions.d.cts.map +1 -1
  20. package/build/legacy/mutationOptions.d.ts +4 -17
  21. package/build/legacy/mutationOptions.d.ts.map +1 -1
  22. package/build/legacy/mutationOptions.js.map +1 -1
  23. package/build/legacy/queryOptions.cjs.map +1 -1
  24. package/build/legacy/queryOptions.d.cts +51 -74
  25. package/build/legacy/queryOptions.d.cts.map +1 -1
  26. package/build/legacy/queryOptions.d.ts +51 -74
  27. package/build/legacy/queryOptions.d.ts.map +1 -1
  28. package/build/legacy/queryOptions.js.map +1 -1
  29. package/build/legacy/useInfiniteQuery.cjs.map +1 -1
  30. package/build/legacy/useInfiniteQuery.d.cts +208 -36
  31. package/build/legacy/useInfiniteQuery.d.cts.map +1 -1
  32. package/build/legacy/useInfiniteQuery.d.ts +208 -36
  33. package/build/legacy/useInfiniteQuery.d.ts.map +1 -1
  34. package/build/legacy/useInfiniteQuery.js.map +1 -1
  35. package/build/legacy/useIsFetching.cjs +8 -6
  36. package/build/legacy/useIsFetching.cjs.map +1 -1
  37. package/build/legacy/useIsFetching.d.cts +8 -6
  38. package/build/legacy/useIsFetching.d.cts.map +1 -1
  39. package/build/legacy/useIsFetching.d.ts +8 -6
  40. package/build/legacy/useIsFetching.d.ts.map +1 -1
  41. package/build/legacy/useIsFetching.js +8 -6
  42. package/build/legacy/useIsFetching.js.map +1 -1
  43. package/build/legacy/useMutation.cjs +13 -11
  44. package/build/legacy/useMutation.cjs.map +1 -1
  45. package/build/legacy/useMutation.d.cts +13 -11
  46. package/build/legacy/useMutation.d.cts.map +1 -1
  47. package/build/legacy/useMutation.d.ts +13 -11
  48. package/build/legacy/useMutation.d.ts.map +1 -1
  49. package/build/legacy/useMutation.js +13 -11
  50. package/build/legacy/useMutation.js.map +1 -1
  51. package/build/legacy/useMutationState.cjs +49 -29
  52. package/build/legacy/useMutationState.cjs.map +1 -1
  53. package/build/legacy/useMutationState.d.cts +49 -29
  54. package/build/legacy/useMutationState.d.cts.map +1 -1
  55. package/build/legacy/useMutationState.d.ts +49 -29
  56. package/build/legacy/useMutationState.d.ts.map +1 -1
  57. package/build/legacy/useMutationState.js +49 -29
  58. package/build/legacy/useMutationState.js.map +1 -1
  59. package/build/legacy/useQueries.cjs +50 -23
  60. package/build/legacy/useQueries.cjs.map +1 -1
  61. package/build/legacy/useQueries.d.cts +50 -23
  62. package/build/legacy/useQueries.d.cts.map +1 -1
  63. package/build/legacy/useQueries.d.ts +50 -23
  64. package/build/legacy/useQueries.d.ts.map +1 -1
  65. package/build/legacy/useQueries.js +50 -23
  66. package/build/legacy/useQueries.js.map +1 -1
  67. package/build/legacy/useQuery.cjs.map +1 -1
  68. package/build/legacy/useQuery.d.cts +93 -33
  69. package/build/legacy/useQuery.d.cts.map +1 -1
  70. package/build/legacy/useQuery.d.ts +93 -33
  71. package/build/legacy/useQuery.d.ts.map +1 -1
  72. package/build/legacy/useQuery.js.map +1 -1
  73. package/build/legacy/useSuspenseInfiniteQuery.cjs +57 -7
  74. package/build/legacy/useSuspenseInfiniteQuery.cjs.map +1 -1
  75. package/build/legacy/useSuspenseInfiniteQuery.d.cts +57 -7
  76. package/build/legacy/useSuspenseInfiniteQuery.d.cts.map +1 -1
  77. package/build/legacy/useSuspenseInfiniteQuery.d.ts +57 -7
  78. package/build/legacy/useSuspenseInfiniteQuery.d.ts.map +1 -1
  79. package/build/legacy/useSuspenseInfiniteQuery.js +57 -7
  80. package/build/legacy/useSuspenseInfiniteQuery.js.map +1 -1
  81. package/build/legacy/useSuspenseQueries.cjs.map +1 -1
  82. package/build/legacy/useSuspenseQueries.d.cts +244 -20
  83. package/build/legacy/useSuspenseQueries.d.cts.map +1 -1
  84. package/build/legacy/useSuspenseQueries.d.ts +244 -20
  85. package/build/legacy/useSuspenseQueries.d.ts.map +1 -1
  86. package/build/legacy/useSuspenseQueries.js.map +1 -1
  87. package/build/legacy/useSuspenseQuery.cjs +48 -8
  88. package/build/legacy/useSuspenseQuery.cjs.map +1 -1
  89. package/build/legacy/useSuspenseQuery.d.cts +48 -8
  90. package/build/legacy/useSuspenseQuery.d.cts.map +1 -1
  91. package/build/legacy/useSuspenseQuery.d.ts +48 -8
  92. package/build/legacy/useSuspenseQuery.d.ts.map +1 -1
  93. package/build/legacy/useSuspenseQuery.js +48 -8
  94. package/build/legacy/useSuspenseQuery.js.map +1 -1
  95. package/build/modern/HydrationBoundary.cjs +1 -1
  96. package/build/modern/HydrationBoundary.cjs.map +1 -1
  97. package/build/modern/HydrationBoundary.js +1 -1
  98. package/build/modern/HydrationBoundary.js.map +1 -1
  99. package/build/modern/QueryErrorResetBoundary.cjs +12 -12
  100. package/build/modern/QueryErrorResetBoundary.cjs.map +1 -1
  101. package/build/modern/QueryErrorResetBoundary.d.cts +12 -12
  102. package/build/modern/QueryErrorResetBoundary.d.ts +12 -12
  103. package/build/modern/QueryErrorResetBoundary.js +12 -12
  104. package/build/modern/QueryErrorResetBoundary.js.map +1 -1
  105. package/build/modern/infiniteQueryOptions.cjs.map +1 -1
  106. package/build/modern/infiniteQueryOptions.d.cts +41 -55
  107. package/build/modern/infiniteQueryOptions.d.cts.map +1 -1
  108. package/build/modern/infiniteQueryOptions.d.ts +41 -55
  109. package/build/modern/infiniteQueryOptions.d.ts.map +1 -1
  110. package/build/modern/infiniteQueryOptions.js.map +1 -1
  111. package/build/modern/mutationOptions.cjs.map +1 -1
  112. package/build/modern/mutationOptions.d.cts +4 -17
  113. package/build/modern/mutationOptions.d.cts.map +1 -1
  114. package/build/modern/mutationOptions.d.ts +4 -17
  115. package/build/modern/mutationOptions.d.ts.map +1 -1
  116. package/build/modern/mutationOptions.js.map +1 -1
  117. package/build/modern/queryOptions.cjs.map +1 -1
  118. package/build/modern/queryOptions.d.cts +51 -74
  119. package/build/modern/queryOptions.d.cts.map +1 -1
  120. package/build/modern/queryOptions.d.ts +51 -74
  121. package/build/modern/queryOptions.d.ts.map +1 -1
  122. package/build/modern/queryOptions.js.map +1 -1
  123. package/build/modern/useInfiniteQuery.cjs.map +1 -1
  124. package/build/modern/useInfiniteQuery.d.cts +208 -36
  125. package/build/modern/useInfiniteQuery.d.cts.map +1 -1
  126. package/build/modern/useInfiniteQuery.d.ts +208 -36
  127. package/build/modern/useInfiniteQuery.d.ts.map +1 -1
  128. package/build/modern/useInfiniteQuery.js.map +1 -1
  129. package/build/modern/useIsFetching.cjs +8 -6
  130. package/build/modern/useIsFetching.cjs.map +1 -1
  131. package/build/modern/useIsFetching.d.cts +8 -6
  132. package/build/modern/useIsFetching.d.cts.map +1 -1
  133. package/build/modern/useIsFetching.d.ts +8 -6
  134. package/build/modern/useIsFetching.d.ts.map +1 -1
  135. package/build/modern/useIsFetching.js +8 -6
  136. package/build/modern/useIsFetching.js.map +1 -1
  137. package/build/modern/useMutation.cjs +13 -11
  138. package/build/modern/useMutation.cjs.map +1 -1
  139. package/build/modern/useMutation.d.cts +13 -11
  140. package/build/modern/useMutation.d.cts.map +1 -1
  141. package/build/modern/useMutation.d.ts +13 -11
  142. package/build/modern/useMutation.d.ts.map +1 -1
  143. package/build/modern/useMutation.js +13 -11
  144. package/build/modern/useMutation.js.map +1 -1
  145. package/build/modern/useMutationState.cjs +49 -29
  146. package/build/modern/useMutationState.cjs.map +1 -1
  147. package/build/modern/useMutationState.d.cts +49 -29
  148. package/build/modern/useMutationState.d.cts.map +1 -1
  149. package/build/modern/useMutationState.d.ts +49 -29
  150. package/build/modern/useMutationState.d.ts.map +1 -1
  151. package/build/modern/useMutationState.js +49 -29
  152. package/build/modern/useMutationState.js.map +1 -1
  153. package/build/modern/useQueries.cjs +50 -23
  154. package/build/modern/useQueries.cjs.map +1 -1
  155. package/build/modern/useQueries.d.cts +50 -23
  156. package/build/modern/useQueries.d.cts.map +1 -1
  157. package/build/modern/useQueries.d.ts +50 -23
  158. package/build/modern/useQueries.d.ts.map +1 -1
  159. package/build/modern/useQueries.js +50 -23
  160. package/build/modern/useQueries.js.map +1 -1
  161. package/build/modern/useQuery.cjs.map +1 -1
  162. package/build/modern/useQuery.d.cts +93 -33
  163. package/build/modern/useQuery.d.cts.map +1 -1
  164. package/build/modern/useQuery.d.ts +93 -33
  165. package/build/modern/useQuery.d.ts.map +1 -1
  166. package/build/modern/useQuery.js.map +1 -1
  167. package/build/modern/useSuspenseInfiniteQuery.cjs +57 -7
  168. package/build/modern/useSuspenseInfiniteQuery.cjs.map +1 -1
  169. package/build/modern/useSuspenseInfiniteQuery.d.cts +57 -7
  170. package/build/modern/useSuspenseInfiniteQuery.d.cts.map +1 -1
  171. package/build/modern/useSuspenseInfiniteQuery.d.ts +57 -7
  172. package/build/modern/useSuspenseInfiniteQuery.d.ts.map +1 -1
  173. package/build/modern/useSuspenseInfiniteQuery.js +57 -7
  174. package/build/modern/useSuspenseInfiniteQuery.js.map +1 -1
  175. package/build/modern/useSuspenseQueries.cjs.map +1 -1
  176. package/build/modern/useSuspenseQueries.d.cts +244 -20
  177. package/build/modern/useSuspenseQueries.d.cts.map +1 -1
  178. package/build/modern/useSuspenseQueries.d.ts +244 -20
  179. package/build/modern/useSuspenseQueries.d.ts.map +1 -1
  180. package/build/modern/useSuspenseQueries.js.map +1 -1
  181. package/build/modern/useSuspenseQuery.cjs +48 -8
  182. package/build/modern/useSuspenseQuery.cjs.map +1 -1
  183. package/build/modern/useSuspenseQuery.d.cts +48 -8
  184. package/build/modern/useSuspenseQuery.d.cts.map +1 -1
  185. package/build/modern/useSuspenseQuery.d.ts +48 -8
  186. package/build/modern/useSuspenseQuery.d.ts.map +1 -1
  187. package/build/modern/useSuspenseQuery.js +48 -8
  188. package/build/modern/useSuspenseQuery.js.map +1 -1
  189. package/build/query-codemods/eslint.config.js +7 -0
  190. package/build/query-codemods/root.eslint.config.js +45 -0
  191. package/package.json +11 -11
  192. package/src/HydrationBoundary.tsx +0 -1
  193. package/src/QueryErrorResetBoundary.tsx +12 -12
  194. package/src/infiniteQueryOptions.ts +41 -55
  195. package/src/mutationOptions.ts +4 -17
  196. package/src/queryOptions.ts +50 -73
  197. package/src/useInfiniteQuery.ts +208 -36
  198. package/src/useIsFetching.ts +8 -6
  199. package/src/useMutation.ts +13 -11
  200. package/src/useMutationState.ts +49 -29
  201. package/src/useQueries.ts +50 -23
  202. package/src/useQuery.ts +93 -33
  203. package/src/useSuspenseInfiniteQuery.ts +57 -7
  204. package/src/useSuspenseQueries.ts +244 -20
  205. package/src/useSuspenseQuery.ts +48 -8
@@ -1 +1 @@
1
- {"version":3,"file":"useMutation.cjs","names":["useQueryClient","useState","MutationObserver","useSyncExternalStore","useCallback","notifyManager","noop","shouldThrowError"],"sources":["../../src/useMutation.ts"],"sourcesContent":["import {\n MutationObserver,\n noop,\n notifyManager,\n shouldThrowError,\n} from '@tanstack/query-core'\nimport type { DefaultError, QueryClient } from '@tanstack/query-core'\nimport { useCallback, useEffect, useState } from 'preact/hooks'\n\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n UseMutateFunction,\n UseMutationOptions,\n UseMutationResult,\n} from './types'\nimport { useSyncExternalStore } from './utils'\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.\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. If you make multiple requests, `onSuccess` will fire only after the latest call you've\n * made.\n *\n * @example\n * ```tsx\n * import { useMutation, useQueryClient } from '@tanstack/preact-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/preact-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/preact-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 `context` if the mutation fails.\n * return { previousTodos }\n * },\n * onError: (_err, _newTodo, context) => {\n * queryClient.setQueryData(['todos'], context?.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:\n * ```tsx\n * import { useMutation, useQueryClient } from '@tanstack/preact-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/preact-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 results = await Promise.allSettled(\n * todos.map((todo) => addMutation.mutateAsync(todo)),\n * )\n *\n * results.forEach((result, index) => {\n * if (result.status === 'rejected') {\n * console.error(`Failed to add \"${todos[index]}\":`, result.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] = useState(\n () =>\n new MutationObserver<TData, TError, TVariables, TOnMutateResult>(\n client,\n options,\n ),\n )\n\n useEffect(() => {\n observer.setOptions(options)\n }, [observer, options])\n\n const result = useSyncExternalStore(\n useCallback(\n (onStoreChange) =>\n observer.subscribe(notifyManager.batchCalls(onStoreChange)),\n [observer],\n ),\n () => observer.getCurrentResult(),\n )\n\n const mutate = 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6LA,SAAgB,YAMd,SACA,aAC+D;CAC/D,MAAM,SAASA,4BAAAA,eAAe,WAAW;CAEzC,MAAM,CAAC,aAAA,GAAYC,aAAAA,SAAAA,OAEf,IAAIC,qBAAAA,iBACF,QACA,OACF,CACJ;CAEA,CAAA,GAAA,aAAA,UAAA,OAAgB;EACd,SAAS,WAAW,OAAO;CAC7B,GAAG,CAAC,UAAU,OAAO,CAAC;CAEtB,MAAM,SAASC,cAAAA,sBAAAA,GACbC,aAAAA,YAAAA,EACG,kBACC,SAAS,UAAUC,qBAAAA,cAAc,WAAW,aAAa,CAAC,GAC5D,CAAC,QAAQ,CACX,SACM,SAAS,iBAAiB,CAClC;CAEA,MAAM,UAAA,GAASD,aAAAA,YAAAA,EAIX,GAAG,SAGA;EACH,SAAS,OAAO,KAAK,IAAkB,KAAK,EAAE,CAAC,CAAC,MAAME,qBAAAA,IAAI;CAC5D,GACA,CAAC,QAAQ,CACX;CAEA,IACE,OAAO,UAAA,GACPC,qBAAAA,iBAAAA,CAAiB,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.cjs","names":["useQueryClient","useState","MutationObserver","useSyncExternalStore","useCallback","notifyManager","noop","shouldThrowError"],"sources":["../../src/useMutation.ts"],"sourcesContent":["import {\n MutationObserver,\n noop,\n notifyManager,\n shouldThrowError,\n} from '@tanstack/query-core'\nimport type { DefaultError, QueryClient } from '@tanstack/query-core'\nimport { useCallback, useEffect, useState } from 'preact/hooks'\n\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n UseMutateFunction,\n UseMutationOptions,\n UseMutationResult,\n} from './types'\nimport { useSyncExternalStore } from './utils'\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/preact-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/preact-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/preact-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/preact-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/preact-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] = useState(\n () =>\n new MutationObserver<TData, TError, TVariables, TOnMutateResult>(\n client,\n options,\n ),\n )\n\n useEffect(() => {\n observer.setOptions(options)\n }, [observer, options])\n\n const result = useSyncExternalStore(\n useCallback(\n (onStoreChange) =>\n observer.subscribe(notifyManager.batchCalls(onStoreChange)),\n [observer],\n ),\n () => observer.getCurrentResult(),\n )\n\n const mutate = 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+LA,SAAgB,YAMd,SACA,aAC+D;CAC/D,MAAM,SAASA,4BAAAA,eAAe,WAAW;CAEzC,MAAM,CAAC,aAAA,GAAYC,aAAAA,SAAAA,OAEf,IAAIC,qBAAAA,iBACF,QACA,OACF,CACJ;CAEA,CAAA,GAAA,aAAA,UAAA,OAAgB;EACd,SAAS,WAAW,OAAO;CAC7B,GAAG,CAAC,UAAU,OAAO,CAAC;CAEtB,MAAM,SAASC,cAAAA,sBAAAA,GACbC,aAAAA,YAAAA,EACG,kBACC,SAAS,UAAUC,qBAAAA,cAAc,WAAW,aAAa,CAAC,GAC5D,CAAC,QAAQ,CACX,SACM,SAAS,iBAAiB,CAClC;CAEA,MAAM,UAAA,GAASD,aAAAA,YAAAA,EAIX,GAAG,SAGA;EACH,SAAS,OAAO,KAAK,IAAkB,KAAK,EAAE,CAAC,CAAC,MAAME,qBAAAA,IAAI;CAC5D,GACA,CAAC,QAAQ,CACX;CAEA,IACE,OAAO,UAAA,GACPC,qBAAAA,iBAAAA,CAAiB,SAAS,QAAQ,cAAc,CAAC,OAAO,KAAK,CAAC,GAE9D,MAAM,OAAO;CAGf,OAAO;EAAE,GAAG;EAAQ;EAAQ,aAAa,OAAO;CAAO;AACzD"}
@@ -5,14 +5,16 @@ import { DefaultError, QueryClient } from "@tanstack/query-core";
5
5
  * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
6
6
  * `useMutation` is the hook for that.
7
7
  *
8
- * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites.
8
+ * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites, or to look
9
+ * the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).
9
10
  * @param options - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`.
10
11
  * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
11
12
  * be used.
12
13
  * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
13
14
  * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
14
- * mutation definition. If you make multiple requests, `onSuccess` will fire only after the latest call you've
15
- * made.
15
+ * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
16
+ * fire only for the latest call you've made, and only while the component is still mounted — unmounting before
17
+ * the mutation settles removes the subscription and prevents them from firing.
16
18
  *
17
19
  * @example
18
20
  * ```tsx
@@ -89,11 +91,11 @@ import { DefaultError, QueryClient } from "@tanstack/query-core";
89
91
  * newTodo,
90
92
  * ])
91
93
  *
92
- * // Passed to `onError` as `context` if the mutation fails.
94
+ * // Passed to `onError` as `onMutateResult` if the mutation fails.
93
95
  * return { previousTodos }
94
96
  * },
95
- * onError: (_err, _newTodo, context) => {
96
- * queryClient.setQueryData(['todos'], context?.previousTodos)
97
+ * onError: (_err, _newTodo, onMutateResult) => {
98
+ * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
97
99
  * },
98
100
  * onSettled: () => {
99
101
  * queryClient.invalidateQueries({ queryKey: ['todos'] })
@@ -108,7 +110,7 @@ import { DefaultError, QueryClient } from "@tanstack/query-core";
108
110
  *
109
111
  * @example
110
112
  * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a
111
- * promise per call instead, so you can wait for all of them:
113
+ * promise per call instead, so you can wait for all of them when they succeed:
112
114
  * ```tsx
113
115
  * import { useMutation, useQueryClient } from '@tanstack/preact-query'
114
116
  *
@@ -152,13 +154,13 @@ import { DefaultError, QueryClient } from "@tanstack/query-core";
152
154
  * })
153
155
  *
154
156
  * async function handleAddAll(todos: Array<string>) {
155
- * const results = await Promise.allSettled(
157
+ * const addResults = await Promise.allSettled(
156
158
  * todos.map((todo) => addMutation.mutateAsync(todo)),
157
159
  * )
158
160
  *
159
- * results.forEach((result, index) => {
160
- * if (result.status === 'rejected') {
161
- * console.error(`Failed to add "${todos[index]}":`, result.reason)
161
+ * addResults.forEach((addResult, index) => {
162
+ * if (addResult.status === 'rejected') {
163
+ * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
162
164
  * }
163
165
  * })
164
166
  * }
@@ -1 +1 @@
1
- {"version":3,"file":"useMutation.d.cts","names":[],"sources":["../../src/useMutation.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6LgB,YACd,iBACA,SAAS,cACT,mBACA,2BAEA,SAAS,mBAAmB,OAAO,QAAQ,YAAY,kBACvD,cAAc,cACb,kBAAkB,OAAO,QAAQ,YAAY"}
1
+ {"version":3,"file":"useMutation.d.cts","names":[],"sources":["../../src/useMutation.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+LgB,YACd,iBACA,SAAS,cACT,mBACA,2BAEA,SAAS,mBAAmB,OAAO,QAAQ,YAAY,kBACvD,cAAc,cACb,kBAAkB,OAAO,QAAQ,YAAY"}
@@ -5,14 +5,16 @@ import { DefaultError, QueryClient } from "@tanstack/query-core";
5
5
  * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
6
6
  * `useMutation` is the hook for that.
7
7
  *
8
- * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites.
8
+ * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites, or to look
9
+ * the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).
9
10
  * @param options - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`.
10
11
  * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
11
12
  * be used.
12
13
  * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
13
14
  * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
14
- * mutation definition. If you make multiple requests, `onSuccess` will fire only after the latest call you've
15
- * made.
15
+ * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
16
+ * fire only for the latest call you've made, and only while the component is still mounted — unmounting before
17
+ * the mutation settles removes the subscription and prevents them from firing.
16
18
  *
17
19
  * @example
18
20
  * ```tsx
@@ -89,11 +91,11 @@ import { DefaultError, QueryClient } from "@tanstack/query-core";
89
91
  * newTodo,
90
92
  * ])
91
93
  *
92
- * // Passed to `onError` as `context` if the mutation fails.
94
+ * // Passed to `onError` as `onMutateResult` if the mutation fails.
93
95
  * return { previousTodos }
94
96
  * },
95
- * onError: (_err, _newTodo, context) => {
96
- * queryClient.setQueryData(['todos'], context?.previousTodos)
97
+ * onError: (_err, _newTodo, onMutateResult) => {
98
+ * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
97
99
  * },
98
100
  * onSettled: () => {
99
101
  * queryClient.invalidateQueries({ queryKey: ['todos'] })
@@ -108,7 +110,7 @@ import { DefaultError, QueryClient } from "@tanstack/query-core";
108
110
  *
109
111
  * @example
110
112
  * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a
111
- * promise per call instead, so you can wait for all of them:
113
+ * promise per call instead, so you can wait for all of them when they succeed:
112
114
  * ```tsx
113
115
  * import { useMutation, useQueryClient } from '@tanstack/preact-query'
114
116
  *
@@ -152,13 +154,13 @@ import { DefaultError, QueryClient } from "@tanstack/query-core";
152
154
  * })
153
155
  *
154
156
  * async function handleAddAll(todos: Array<string>) {
155
- * const results = await Promise.allSettled(
157
+ * const addResults = await Promise.allSettled(
156
158
  * todos.map((todo) => addMutation.mutateAsync(todo)),
157
159
  * )
158
160
  *
159
- * results.forEach((result, index) => {
160
- * if (result.status === 'rejected') {
161
- * console.error(`Failed to add "${todos[index]}":`, result.reason)
161
+ * addResults.forEach((addResult, index) => {
162
+ * if (addResult.status === 'rejected') {
163
+ * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
162
164
  * }
163
165
  * })
164
166
  * }
@@ -1 +1 @@
1
- {"version":3,"file":"useMutation.d.ts","names":[],"sources":["../../src/useMutation.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6LgB,YACd,iBACA,SAAS,cACT,mBACA,2BAEA,SAAS,mBAAmB,OAAO,QAAQ,YAAY,kBACvD,cAAc,cACb,kBAAkB,OAAO,QAAQ,YAAY"}
1
+ {"version":3,"file":"useMutation.d.ts","names":[],"sources":["../../src/useMutation.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+LgB,YACd,iBACA,SAAS,cACT,mBACA,2BAEA,SAAS,mBAAmB,OAAO,QAAQ,YAAY,kBACvD,cAAc,cACb,kBAAkB,OAAO,QAAQ,YAAY"}
@@ -7,14 +7,16 @@ import { useCallback, useEffect, useState } from "preact/hooks";
7
7
  * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
8
8
  * `useMutation` is the hook for that.
9
9
  *
10
- * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites.
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`).
11
12
  * @param options - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`.
12
13
  * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
13
14
  * be used.
14
15
  * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
15
16
  * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
16
- * mutation definition. If you make multiple requests, `onSuccess` will fire only after the latest call you've
17
- * made.
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.
18
20
  *
19
21
  * @example
20
22
  * ```tsx
@@ -91,11 +93,11 @@ import { useCallback, useEffect, useState } from "preact/hooks";
91
93
  * newTodo,
92
94
  * ])
93
95
  *
94
- * // Passed to `onError` as `context` if the mutation fails.
96
+ * // Passed to `onError` as `onMutateResult` if the mutation fails.
95
97
  * return { previousTodos }
96
98
  * },
97
- * onError: (_err, _newTodo, context) => {
98
- * queryClient.setQueryData(['todos'], context?.previousTodos)
99
+ * onError: (_err, _newTodo, onMutateResult) => {
100
+ * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
99
101
  * },
100
102
  * onSettled: () => {
101
103
  * queryClient.invalidateQueries({ queryKey: ['todos'] })
@@ -110,7 +112,7 @@ import { useCallback, useEffect, useState } from "preact/hooks";
110
112
  *
111
113
  * @example
112
114
  * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a
113
- * promise per call instead, so you can wait for all of them:
115
+ * promise per call instead, so you can wait for all of them when they succeed:
114
116
  * ```tsx
115
117
  * import { useMutation, useQueryClient } from '@tanstack/preact-query'
116
118
  *
@@ -154,13 +156,13 @@ import { useCallback, useEffect, useState } from "preact/hooks";
154
156
  * })
155
157
  *
156
158
  * async function handleAddAll(todos: Array<string>) {
157
- * const results = await Promise.allSettled(
159
+ * const addResults = await Promise.allSettled(
158
160
  * todos.map((todo) => addMutation.mutateAsync(todo)),
159
161
  * )
160
162
  *
161
- * results.forEach((result, index) => {
162
- * if (result.status === 'rejected') {
163
- * console.error(`Failed to add "${todos[index]}":`, result.reason)
163
+ * addResults.forEach((addResult, index) => {
164
+ * if (addResult.status === 'rejected') {
165
+ * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
164
166
  * }
165
167
  * })
166
168
  * }
@@ -1 +1 @@
1
- {"version":3,"file":"useMutation.js","names":[],"sources":["../../src/useMutation.ts"],"sourcesContent":["import {\n MutationObserver,\n noop,\n notifyManager,\n shouldThrowError,\n} from '@tanstack/query-core'\nimport type { DefaultError, QueryClient } from '@tanstack/query-core'\nimport { useCallback, useEffect, useState } from 'preact/hooks'\n\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n UseMutateFunction,\n UseMutationOptions,\n UseMutationResult,\n} from './types'\nimport { useSyncExternalStore } from './utils'\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.\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. If you make multiple requests, `onSuccess` will fire only after the latest call you've\n * made.\n *\n * @example\n * ```tsx\n * import { useMutation, useQueryClient } from '@tanstack/preact-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/preact-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/preact-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 `context` if the mutation fails.\n * return { previousTodos }\n * },\n * onError: (_err, _newTodo, context) => {\n * queryClient.setQueryData(['todos'], context?.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:\n * ```tsx\n * import { useMutation, useQueryClient } from '@tanstack/preact-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/preact-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 results = await Promise.allSettled(\n * todos.map((todo) => addMutation.mutateAsync(todo)),\n * )\n *\n * results.forEach((result, index) => {\n * if (result.status === 'rejected') {\n * console.error(`Failed to add \"${todos[index]}\":`, result.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] = useState(\n () =>\n new MutationObserver<TData, TError, TVariables, TOnMutateResult>(\n client,\n options,\n ),\n )\n\n useEffect(() => {\n observer.setOptions(options)\n }, [observer, options])\n\n const result = useSyncExternalStore(\n useCallback(\n (onStoreChange) =>\n observer.subscribe(notifyManager.batchCalls(onStoreChange)),\n [observer],\n ),\n () => observer.getCurrentResult(),\n )\n\n const mutate = 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6LA,SAAgB,YAMd,SACA,aAC+D;CAC/D,MAAM,SAAS,eAAe,WAAW;CAEzC,MAAM,CAAC,YAAY,eAEf,IAAI,iBACF,QACA,OACF,CACJ;CAEA,gBAAgB;EACd,SAAS,WAAW,OAAO;CAC7B,GAAG,CAAC,UAAU,OAAO,CAAC;CAEtB,MAAM,SAAS,qBACb,aACG,kBACC,SAAS,UAAU,cAAc,WAAW,aAAa,CAAC,GAC5D,CAAC,QAAQ,CACX,SACM,SAAS,iBAAiB,CAClC;CAEA,MAAM,SAAS,aAIX,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":["import {\n MutationObserver,\n noop,\n notifyManager,\n shouldThrowError,\n} from '@tanstack/query-core'\nimport type { DefaultError, QueryClient } from '@tanstack/query-core'\nimport { useCallback, useEffect, useState } from 'preact/hooks'\n\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n UseMutateFunction,\n UseMutationOptions,\n UseMutationResult,\n} from './types'\nimport { useSyncExternalStore } from './utils'\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/preact-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/preact-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/preact-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/preact-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/preact-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] = useState(\n () =>\n new MutationObserver<TData, TError, TVariables, TOnMutateResult>(\n client,\n options,\n ),\n )\n\n useEffect(() => {\n observer.setOptions(options)\n }, [observer, options])\n\n const result = useSyncExternalStore(\n useCallback(\n (onStoreChange) =>\n observer.subscribe(notifyManager.batchCalls(onStoreChange)),\n [observer],\n ),\n () => observer.getCurrentResult(),\n )\n\n const mutate = 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+LA,SAAgB,YAMd,SACA,aAC+D;CAC/D,MAAM,SAAS,eAAe,WAAW;CAEzC,MAAM,CAAC,YAAY,eAEf,IAAI,iBACF,QACA,OACF,CACJ;CAEA,gBAAgB;EACd,SAAS,WAAW,OAAO;CAC7B,GAAG,CAAC,UAAU,OAAO,CAAC;CAEtB,MAAM,SAAS,qBACb,aACG,kBACC,SAAS,UAAU,cAAc,WAAW,aAAa,CAAC,GAC5D,CAAC,QAAQ,CACX,SACM,SAAS,iBAAiB,CAClC;CAEA,MAAM,SAAS,aAIX,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"}
@@ -5,22 +5,24 @@ let _tanstack_query_core = require("@tanstack/query-core");
5
5
  let preact_hooks = require("preact/hooks");
6
6
  //#region src/useMutationState.ts
7
7
  /**
8
- * `useIsMutating` is an optional hook that returns the `number` of mutations that your application is fetching
8
+ * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`
9
9
  * (useful for app-wide loading indicators).
10
10
  *
11
11
  * @param filters - The {@link MutationFilters} to narrow down the matched mutations.
12
12
  * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
13
13
  * be used.
14
- * @returns Will be the `number` of the mutations that your application is currently fetching.
14
+ * @returns Will be the `number` of the mutations that your application currently has `pending`.
15
15
  *
16
16
  * @example
17
17
  * ```tsx
18
18
  * import { useIsMutating } from '@tanstack/preact-query'
19
19
  *
20
- * // How many mutations are fetching?
21
- * const isMutating = useIsMutating()
22
- * // How many mutations matching the posts prefix are fetching?
23
- * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
20
+ * function PostsMutatingIndicator() {
21
+ * // How many mutations matching the posts prefix are in progress?
22
+ * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
23
+ *
24
+ * return isMutatingPosts ? <span>Saving posts...</span> : null
25
+ * }
24
26
  * ```
25
27
  */
26
28
  function useIsMutating(filters, queryClient) {
@@ -49,10 +51,14 @@ function getResult(mutationCache, options) {
49
51
  * ```tsx
50
52
  * import { useMutationState } from '@tanstack/preact-query'
51
53
  *
52
- * const variables = useMutationState({
53
- * filters: { status: 'pending' },
54
- * select: (mutation) => mutation.state.variables,
55
- * })
54
+ * function PendingPosts() {
55
+ * const pendingVariables = useMutationState({
56
+ * filters: { status: 'pending' },
57
+ * select: (mutation) => mutation.state.variables,
58
+ * })
59
+ *
60
+ * return <>{pendingVariables.length} posts saving...</>
61
+ * }
56
62
  * ```
57
63
  *
58
64
  * @example
@@ -62,30 +68,44 @@ function getResult(mutationCache, options) {
62
68
  *
63
69
  * const mutationKey = ['posts']
64
70
  *
65
- * // Some mutation that we want to get the state for
66
- * const mutation = useMutation({
67
- * mutationKey,
68
- * mutationFn: createPosts,
69
- * })
70
- *
71
- * const data = useMutationState({
72
- * // this mutation key needs to match the mutation key of the given mutation (see above)
73
- * filters: { mutationKey },
74
- * select: (mutation) => mutation.state.data,
75
- * })
71
+ * function Posts() {
72
+ * // Some mutation that we want to get the state for
73
+ * const mutation = useMutation({
74
+ * mutationKey,
75
+ * mutationFn: createPosts,
76
+ * })
77
+ *
78
+ * const savedPosts = useMutationState({
79
+ * // this mutation key needs to match the mutation key of the given mutation (see above)
80
+ * filters: { mutationKey, status: 'success' },
81
+ * select: (mutation) => mutation.state.data,
82
+ * })
83
+ *
84
+ * return (
85
+ * <button onClick={() => mutation.mutate(['New Post'])}>
86
+ * Create post ({savedPosts.length} saved so far)
87
+ * </button>
88
+ * )
89
+ * }
76
90
  * ```
77
91
  *
78
92
  * @example
79
- * Access the latest mutation data via the `mutationKey`. Each invocation of `mutate` adds a new entry to the
80
- * mutation cache for `gcTime` milliseconds — check the last item that `useMutationState` returns to get the
81
- * latest invocation:
93
+ * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
94
+ * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the
95
+ * last item that `useMutationState` returns to get the latest successful invocation:
82
96
  * ```tsx
83
- * const data = useMutationState({
84
- * filters: { mutationKey: ['posts'] },
85
- * select: (mutation) => mutation.state.data,
86
- * })
97
+ * import { useMutationState } from '@tanstack/preact-query'
98
+ *
99
+ * function LatestPost() {
100
+ * const savedPosts = useMutationState({
101
+ * filters: { mutationKey: ['posts'], status: 'success' },
102
+ * select: (mutation) => mutation.state.data,
103
+ * })
104
+ *
105
+ * const latestSavedPost = savedPosts[savedPosts.length - 1]
87
106
  *
88
- * const latest = data[data.length - 1]
107
+ * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>
108
+ * }
89
109
  * ```
90
110
  */
91
111
  function useMutationState(options = {}, queryClient) {
@@ -1 +1 @@
1
- {"version":3,"file":"useMutationState.cjs","names":["useQueryClient","useRef","useSyncExternalStore","useCallback","replaceEqualDeep"],"sources":["../../src/useMutationState.ts"],"sourcesContent":["import { notifyManager, replaceEqualDeep } from '@tanstack/query-core'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n QueryClient,\n} from '@tanstack/query-core'\nimport { useCallback, useEffect, useRef } from 'preact/hooks'\n\nimport { useQueryClient } from './QueryClientProvider'\nimport { useSyncExternalStore } from './utils'\n\n/**\n * `useIsMutating` is an optional hook that returns the `number` of mutations that your application is fetching\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 is currently fetching.\n *\n * @example\n * ```tsx\n * import { useIsMutating } from '@tanstack/preact-query'\n *\n * // How many mutations are fetching?\n * const isMutating = useIsMutating()\n * // How many mutations matching the posts prefix are fetching?\n * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })\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/preact-query'\n *\n * const variables = useMutationState({\n * filters: { status: 'pending' },\n * select: (mutation) => mutation.state.variables,\n * })\n * ```\n *\n * @example\n * Get all data for specific mutations via the `mutationKey`:\n * ```tsx\n * import { useMutation, useMutationState } from '@tanstack/preact-query'\n *\n * const mutationKey = ['posts']\n *\n * // Some mutation that we want to get the state for\n * const mutation = useMutation({\n * mutationKey,\n * mutationFn: createPosts,\n * })\n *\n * const data = useMutationState({\n * // this mutation key needs to match the mutation key of the given mutation (see above)\n * filters: { mutationKey },\n * select: (mutation) => mutation.state.data,\n * })\n * ```\n *\n * @example\n * Access the latest mutation data via the `mutationKey`. Each invocation of `mutate` adds a new entry to the\n * mutation cache for `gcTime` milliseconds — check the last item that `useMutationState` returns to get the\n * latest invocation:\n * ```tsx\n * const data = useMutationState({\n * filters: { mutationKey: ['posts'] },\n * select: (mutation) => mutation.state.data,\n * })\n *\n * const latest = data[data.length - 1]\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 = useRef(options)\n const result = useRef<Array<TResult>>(null)\n if (result.current === null) {\n result.current = getResult(mutationCache, options)\n }\n\n useEffect(() => {\n optionsRef.current = options\n })\n\n return useSyncExternalStore(\n 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 )!\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,SAAgB,iBAKd,UAAoD,CAAC,GACrD,aACgB;CAChB,MAAM,gBAAgBA,4BAAAA,eAAe,WAAW,CAAC,CAAC,iBAAiB;CACnE,MAAM,cAAA,GAAaC,aAAAA,OAAAA,CAAO,OAAO;CACjC,MAAM,UAAA,GAASA,aAAAA,OAAAA,CAAuB,IAAI;CAC1C,IAAI,OAAO,YAAY,MACrB,OAAO,UAAU,UAAU,eAAe,OAAO;CAGnD,CAAA,GAAA,aAAA,UAAA,OAAgB;EACd,WAAW,UAAU;CACvB,CAAC;CAED,OAAOC,cAAAA,sBAAAA,GACLC,aAAAA,YAAAA,EACG,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,OACf;AACF"}
1
+ {"version":3,"file":"useMutationState.cjs","names":["useQueryClient","useRef","useSyncExternalStore","useCallback","replaceEqualDeep"],"sources":["../../src/useMutationState.ts"],"sourcesContent":["import { notifyManager, replaceEqualDeep } from '@tanstack/query-core'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n QueryClient,\n} from '@tanstack/query-core'\nimport { useCallback, useEffect, useRef } from 'preact/hooks'\n\nimport { useQueryClient } from './QueryClientProvider'\nimport { useSyncExternalStore } from './utils'\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/preact-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/preact-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/preact-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/preact-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 = useRef(options)\n const result = useRef<Array<TResult>>(null)\n if (result.current === null) {\n result.current = getResult(mutationCache, options)\n }\n\n useEffect(() => {\n optionsRef.current = options\n })\n\n return useSyncExternalStore(\n 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 )!\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,cAAA,GAAaC,aAAAA,OAAAA,CAAO,OAAO;CACjC,MAAM,UAAA,GAASA,aAAAA,OAAAA,CAAuB,IAAI;CAC1C,IAAI,OAAO,YAAY,MACrB,OAAO,UAAU,UAAU,eAAe,OAAO;CAGnD,CAAA,GAAA,aAAA,UAAA,OAAgB;EACd,WAAW,UAAU;CACvB,CAAC;CAED,OAAOC,cAAAA,sBAAAA,GACLC,aAAAA,YAAAA,EACG,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,OACf;AACF"}
@@ -1,22 +1,24 @@
1
1
  import { Mutation, MutationFilters, MutationState, QueryClient } from "@tanstack/query-core";
2
2
  //#region src/useMutationState.d.ts
3
3
  /**
4
- * `useIsMutating` is an optional hook that returns the `number` of mutations that your application is fetching
4
+ * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`
5
5
  * (useful for app-wide loading indicators).
6
6
  *
7
7
  * @param filters - The {@link MutationFilters} to narrow down the matched mutations.
8
8
  * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
9
9
  * be used.
10
- * @returns Will be the `number` of the mutations that your application is currently fetching.
10
+ * @returns Will be the `number` of the mutations that your application currently has `pending`.
11
11
  *
12
12
  * @example
13
13
  * ```tsx
14
14
  * import { useIsMutating } from '@tanstack/preact-query'
15
15
  *
16
- * // How many mutations are fetching?
17
- * const isMutating = useIsMutating()
18
- * // How many mutations matching the posts prefix are fetching?
19
- * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
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
+ * }
20
22
  * ```
21
23
  */
22
24
  declare function useIsMutating(filters?: MutationFilters, queryClient?: QueryClient): number;
@@ -41,10 +43,14 @@ type MutationStateOptions<TResult = MutationState, TMutation extends Mutation<an
41
43
  * ```tsx
42
44
  * import { useMutationState } from '@tanstack/preact-query'
43
45
  *
44
- * const variables = useMutationState({
45
- * filters: { status: 'pending' },
46
- * select: (mutation) => mutation.state.variables,
47
- * })
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
+ * }
48
54
  * ```
49
55
  *
50
56
  * @example
@@ -54,30 +60,44 @@ type MutationStateOptions<TResult = MutationState, TMutation extends Mutation<an
54
60
  *
55
61
  * const mutationKey = ['posts']
56
62
  *
57
- * // Some mutation that we want to get the state for
58
- * const mutation = useMutation({
59
- * mutationKey,
60
- * mutationFn: createPosts,
61
- * })
62
- *
63
- * const data = useMutationState({
64
- * // this mutation key needs to match the mutation key of the given mutation (see above)
65
- * filters: { mutationKey },
66
- * select: (mutation) => mutation.state.data,
67
- * })
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
+ * }
68
82
  * ```
69
83
  *
70
84
  * @example
71
- * Access the latest mutation data via the `mutationKey`. Each invocation of `mutate` adds a new entry to the
72
- * mutation cache for `gcTime` milliseconds — check the last item that `useMutationState` returns to get the
73
- * latest invocation:
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:
74
88
  * ```tsx
75
- * const data = useMutationState({
76
- * filters: { mutationKey: ['posts'] },
77
- * select: (mutation) => mutation.state.data,
78
- * })
89
+ * import { useMutationState } from '@tanstack/preact-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]
79
98
  *
80
- * const latest = data[data.length - 1]
99
+ * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>
100
+ * }
81
101
  * ```
82
102
  */
83
103
  declare function useMutationState<TResult = MutationState, TMutation extends Mutation<any, any, any, any> = MutationTypeFromResult<TResult>>(options?: MutationStateOptions<TResult, TMutation>, queryClient?: QueryClient): Array<TResult>;
@@ -1 +1 @@
1
- {"version":3,"file":"useMutationState.d.cts","names":[],"sources":["../../src/useMutationState.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;iBAgCgB,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA4EpB,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"}