@tanstack/react-query 5.0.0-alpha.9 → 5.0.0-alpha.91

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 (411) hide show
  1. package/build/codemods/remove-overloads/remove-overloads.js +59 -0
  2. package/build/codemods/remove-overloads/transformers/filter-aware-usage-transformer.js +153 -0
  3. package/build/codemods/remove-overloads/transformers/query-fn-aware-usage-transformer.js +188 -0
  4. package/build/codemods/remove-overloads/utils/index.js +124 -0
  5. package/build/codemods/remove-overloads/utils/unknown-usage-error.js +27 -0
  6. package/build/codemods/rename-hydrate/rename-hydrate.js +55 -0
  7. package/build/codemods/rename-properties/rename-properties.js +41 -0
  8. package/build/codemods/src/utils/index.js +205 -0
  9. package/build/codemods/src/v4/key-transformation.js +138 -0
  10. package/build/codemods/src/v4/replace-import-specifier.js +25 -0
  11. package/build/codemods/transformers/query-cache-transformer.js +116 -0
  12. package/build/codemods/transformers/query-client-transformer.js +48 -0
  13. package/build/codemods/transformers/use-query-like-transformer.js +32 -0
  14. package/build/codemods/utils/replacers/key-replacer.js +164 -0
  15. package/build/legacy/HydrationBoundary.cjs +60 -0
  16. package/build/legacy/HydrationBoundary.cjs.map +1 -0
  17. package/build/legacy/HydrationBoundary.d.cts +12 -0
  18. package/build/legacy/HydrationBoundary.d.ts +12 -0
  19. package/build/legacy/HydrationBoundary.js +26 -0
  20. package/build/legacy/HydrationBoundary.js.map +1 -0
  21. package/build/legacy/QueryClientProvider.cjs +71 -0
  22. package/build/legacy/QueryClientProvider.cjs.map +1 -0
  23. package/build/legacy/QueryClientProvider.d.cts +12 -0
  24. package/build/legacy/QueryClientProvider.d.ts +12 -0
  25. package/build/legacy/QueryClientProvider.js +35 -0
  26. package/build/legacy/QueryClientProvider.js.map +1 -0
  27. package/build/legacy/QueryErrorResetBoundary.cjs +66 -0
  28. package/build/legacy/QueryErrorResetBoundary.cjs.map +1 -0
  29. package/build/legacy/QueryErrorResetBoundary.d.cts +14 -0
  30. package/build/legacy/QueryErrorResetBoundary.d.ts +14 -0
  31. package/build/legacy/QueryErrorResetBoundary.js +31 -0
  32. package/build/legacy/QueryErrorResetBoundary.js.map +1 -0
  33. package/build/legacy/errorBoundaryUtils.cjs +67 -0
  34. package/build/legacy/errorBoundaryUtils.cjs.map +1 -0
  35. package/build/legacy/errorBoundaryUtils.d.cts +14 -0
  36. package/build/legacy/errorBoundaryUtils.d.ts +14 -0
  37. package/build/legacy/errorBoundaryUtils.js +31 -0
  38. package/build/legacy/errorBoundaryUtils.js.map +1 -0
  39. package/build/legacy/index.cjs +85 -0
  40. package/build/legacy/index.cjs.map +1 -0
  41. package/build/legacy/index.d.cts +17 -0
  42. package/build/legacy/index.d.ts +17 -0
  43. package/build/legacy/index.js +46 -0
  44. package/build/legacy/index.js.map +1 -0
  45. package/build/legacy/infiniteQueryOptions.cjs +33 -0
  46. package/build/legacy/infiniteQueryOptions.cjs.map +1 -0
  47. package/build/legacy/infiniteQueryOptions.d.cts +13 -0
  48. package/build/legacy/infiniteQueryOptions.d.ts +13 -0
  49. package/build/legacy/infiniteQueryOptions.js +8 -0
  50. package/build/legacy/infiniteQueryOptions.js.map +1 -0
  51. package/build/legacy/isRestoring.cjs +47 -0
  52. package/build/legacy/isRestoring.cjs.map +1 -0
  53. package/build/legacy/isRestoring.d.cts +6 -0
  54. package/build/legacy/isRestoring.d.ts +6 -0
  55. package/build/legacy/isRestoring.js +12 -0
  56. package/build/legacy/isRestoring.js.map +1 -0
  57. package/build/legacy/queryOptions.cjs +33 -0
  58. package/build/legacy/queryOptions.cjs.map +1 -0
  59. package/build/legacy/queryOptions.d.cts +13 -0
  60. package/build/legacy/queryOptions.d.ts +13 -0
  61. package/build/legacy/queryOptions.js +8 -0
  62. package/build/legacy/queryOptions.js.map +1 -0
  63. package/build/legacy/suspense.cjs +48 -0
  64. package/build/legacy/suspense.cjs.map +1 -0
  65. package/build/legacy/suspense.d.cts +10 -0
  66. package/build/legacy/suspense.d.ts +10 -0
  67. package/build/legacy/suspense.js +20 -0
  68. package/build/legacy/suspense.js.map +1 -0
  69. package/build/legacy/types.cjs +19 -0
  70. package/build/legacy/types.cjs.map +1 -0
  71. package/build/legacy/types.d.cts +34 -0
  72. package/build/legacy/types.d.ts +34 -0
  73. package/build/legacy/types.js +1 -0
  74. package/build/legacy/types.js.map +1 -0
  75. package/build/legacy/useBaseQuery.cjs +92 -0
  76. package/build/legacy/useBaseQuery.cjs.map +1 -0
  77. package/build/legacy/useBaseQuery.d.cts +92 -0
  78. package/build/legacy/useBaseQuery.d.ts +92 -0
  79. package/build/legacy/useBaseQuery.js +62 -0
  80. package/build/legacy/useBaseQuery.js.map +1 -0
  81. package/build/legacy/useInfiniteQuery.cjs +41 -0
  82. package/build/legacy/useInfiniteQuery.cjs.map +1 -0
  83. package/build/legacy/useInfiniteQuery.d.cts +8 -0
  84. package/build/legacy/useInfiniteQuery.d.ts +8 -0
  85. package/build/legacy/useInfiniteQuery.js +17 -0
  86. package/build/legacy/useInfiniteQuery.js.map +1 -0
  87. package/build/legacy/useIsFetching.cjs +56 -0
  88. package/build/legacy/useIsFetching.cjs.map +1 -0
  89. package/build/legacy/useIsFetching.d.cts +5 -0
  90. package/build/legacy/useIsFetching.d.ts +5 -0
  91. package/build/legacy/useIsFetching.js +22 -0
  92. package/build/legacy/useIsFetching.js.map +1 -0
  93. package/build/legacy/useMutation.cjs +77 -0
  94. package/build/legacy/useMutation.cjs.map +1 -0
  95. package/build/legacy/useMutation.d.cts +6 -0
  96. package/build/legacy/useMutation.d.ts +6 -0
  97. package/build/legacy/useMutation.js +43 -0
  98. package/build/legacy/useMutation.js.map +1 -0
  99. package/build/legacy/useMutationState.cjs +88 -0
  100. package/build/legacy/useMutationState.cjs.map +1 -0
  101. package/build/legacy/useMutationState.d.cts +10 -0
  102. package/build/legacy/useMutationState.d.ts +10 -0
  103. package/build/legacy/useMutationState.js +53 -0
  104. package/build/legacy/useMutationState.js.map +1 -0
  105. package/build/legacy/useQueries.cjs +128 -0
  106. package/build/legacy/useQueries.cjs.map +1 -0
  107. package/build/legacy/useQueries.d.cts +53 -0
  108. package/build/{lib → legacy}/useQueries.d.ts +14 -11
  109. package/build/legacy/useQueries.js +103 -0
  110. package/build/legacy/useQueries.js.map +1 -0
  111. package/build/legacy/useQuery.cjs +36 -0
  112. package/build/legacy/useQuery.cjs.map +1 -0
  113. package/build/legacy/useQuery.d.cts +8 -0
  114. package/build/legacy/useQuery.d.ts +8 -0
  115. package/build/legacy/useQuery.js +12 -0
  116. package/build/legacy/useQuery.js.map +1 -0
  117. package/build/legacy/useSuspenseInfiniteQuery.cjs +46 -0
  118. package/build/legacy/useSuspenseInfiniteQuery.cjs.map +1 -0
  119. package/build/legacy/useSuspenseInfiniteQuery.d.cts +6 -0
  120. package/build/legacy/useSuspenseInfiniteQuery.d.ts +6 -0
  121. package/build/legacy/useSuspenseInfiniteQuery.js +22 -0
  122. package/build/legacy/useSuspenseInfiniteQuery.js.map +1 -0
  123. package/build/legacy/useSuspenseQuery.cjs +45 -0
  124. package/build/legacy/useSuspenseQuery.cjs.map +1 -0
  125. package/build/legacy/useSuspenseQuery.d.cts +6 -0
  126. package/build/legacy/useSuspenseQuery.d.ts +6 -0
  127. package/build/legacy/useSuspenseQuery.js +21 -0
  128. package/build/legacy/useSuspenseQuery.js.map +1 -0
  129. package/build/legacy/utils.cjs +36 -0
  130. package/build/legacy/utils.cjs.map +1 -0
  131. package/build/legacy/utils.d.cts +3 -0
  132. package/build/legacy/utils.d.ts +3 -0
  133. package/build/legacy/utils.js +11 -0
  134. package/build/legacy/utils.js.map +1 -0
  135. package/build/modern/HydrationBoundary.cjs +60 -0
  136. package/build/modern/HydrationBoundary.cjs.map +1 -0
  137. package/build/modern/HydrationBoundary.d.cts +12 -0
  138. package/build/modern/HydrationBoundary.d.ts +12 -0
  139. package/build/modern/HydrationBoundary.js +26 -0
  140. package/build/modern/HydrationBoundary.js.map +1 -0
  141. package/build/modern/QueryClientProvider.cjs +71 -0
  142. package/build/modern/QueryClientProvider.cjs.map +1 -0
  143. package/build/modern/QueryClientProvider.d.cts +12 -0
  144. package/build/modern/QueryClientProvider.d.ts +12 -0
  145. package/build/modern/QueryClientProvider.js +35 -0
  146. package/build/modern/QueryClientProvider.js.map +1 -0
  147. package/build/modern/QueryErrorResetBoundary.cjs +66 -0
  148. package/build/modern/QueryErrorResetBoundary.cjs.map +1 -0
  149. package/build/modern/QueryErrorResetBoundary.d.cts +14 -0
  150. package/build/modern/QueryErrorResetBoundary.d.ts +14 -0
  151. package/build/modern/QueryErrorResetBoundary.js +31 -0
  152. package/build/modern/QueryErrorResetBoundary.js.map +1 -0
  153. package/build/modern/errorBoundaryUtils.cjs +67 -0
  154. package/build/modern/errorBoundaryUtils.cjs.map +1 -0
  155. package/build/modern/errorBoundaryUtils.d.cts +14 -0
  156. package/build/modern/errorBoundaryUtils.d.ts +14 -0
  157. package/build/modern/errorBoundaryUtils.js +31 -0
  158. package/build/modern/errorBoundaryUtils.js.map +1 -0
  159. package/build/modern/index.cjs +85 -0
  160. package/build/modern/index.cjs.map +1 -0
  161. package/build/modern/index.d.cts +17 -0
  162. package/build/modern/index.d.ts +17 -0
  163. package/build/modern/index.js +46 -0
  164. package/build/modern/index.js.map +1 -0
  165. package/build/modern/infiniteQueryOptions.cjs +33 -0
  166. package/build/modern/infiniteQueryOptions.cjs.map +1 -0
  167. package/build/modern/infiniteQueryOptions.d.cts +13 -0
  168. package/build/modern/infiniteQueryOptions.d.ts +13 -0
  169. package/build/modern/infiniteQueryOptions.js +8 -0
  170. package/build/modern/infiniteQueryOptions.js.map +1 -0
  171. package/build/modern/isRestoring.cjs +47 -0
  172. package/build/modern/isRestoring.cjs.map +1 -0
  173. package/build/modern/isRestoring.d.cts +6 -0
  174. package/build/modern/isRestoring.d.ts +6 -0
  175. package/build/modern/isRestoring.js +12 -0
  176. package/build/modern/isRestoring.js.map +1 -0
  177. package/build/modern/queryOptions.cjs +33 -0
  178. package/build/modern/queryOptions.cjs.map +1 -0
  179. package/build/modern/queryOptions.d.cts +13 -0
  180. package/build/modern/queryOptions.d.ts +13 -0
  181. package/build/modern/queryOptions.js +8 -0
  182. package/build/modern/queryOptions.js.map +1 -0
  183. package/build/modern/suspense.cjs +48 -0
  184. package/build/modern/suspense.cjs.map +1 -0
  185. package/build/modern/suspense.d.cts +10 -0
  186. package/build/modern/suspense.d.ts +10 -0
  187. package/build/modern/suspense.js +20 -0
  188. package/build/modern/suspense.js.map +1 -0
  189. package/build/modern/types.cjs +19 -0
  190. package/build/modern/types.cjs.map +1 -0
  191. package/build/modern/types.d.cts +34 -0
  192. package/build/modern/types.d.ts +34 -0
  193. package/build/modern/types.js +1 -0
  194. package/build/modern/types.js.map +1 -0
  195. package/build/modern/useBaseQuery.cjs +92 -0
  196. package/build/modern/useBaseQuery.cjs.map +1 -0
  197. package/build/modern/useBaseQuery.d.cts +92 -0
  198. package/build/modern/useBaseQuery.d.ts +92 -0
  199. package/build/modern/useBaseQuery.js +62 -0
  200. package/build/modern/useBaseQuery.js.map +1 -0
  201. package/build/modern/useInfiniteQuery.cjs +41 -0
  202. package/build/modern/useInfiniteQuery.cjs.map +1 -0
  203. package/build/modern/useInfiniteQuery.d.cts +8 -0
  204. package/build/modern/useInfiniteQuery.d.ts +8 -0
  205. package/build/modern/useInfiniteQuery.js +17 -0
  206. package/build/modern/useInfiniteQuery.js.map +1 -0
  207. package/build/modern/useIsFetching.cjs +56 -0
  208. package/build/modern/useIsFetching.cjs.map +1 -0
  209. package/build/modern/useIsFetching.d.cts +5 -0
  210. package/build/modern/useIsFetching.d.ts +5 -0
  211. package/build/modern/useIsFetching.js +22 -0
  212. package/build/modern/useIsFetching.js.map +1 -0
  213. package/build/modern/useMutation.cjs +77 -0
  214. package/build/modern/useMutation.cjs.map +1 -0
  215. package/build/modern/useMutation.d.cts +6 -0
  216. package/build/modern/useMutation.d.ts +6 -0
  217. package/build/modern/useMutation.js +43 -0
  218. package/build/modern/useMutation.js.map +1 -0
  219. package/build/modern/useMutationState.cjs +88 -0
  220. package/build/modern/useMutationState.cjs.map +1 -0
  221. package/build/modern/useMutationState.d.cts +10 -0
  222. package/build/modern/useMutationState.d.ts +10 -0
  223. package/build/modern/useMutationState.js +53 -0
  224. package/build/modern/useMutationState.js.map +1 -0
  225. package/build/modern/useQueries.cjs +125 -0
  226. package/build/modern/useQueries.cjs.map +1 -0
  227. package/build/modern/useQueries.d.cts +53 -0
  228. package/build/modern/useQueries.d.ts +53 -0
  229. package/build/modern/useQueries.js +100 -0
  230. package/build/modern/useQueries.js.map +1 -0
  231. package/build/modern/useQuery.cjs +36 -0
  232. package/build/modern/useQuery.cjs.map +1 -0
  233. package/build/modern/useQuery.d.cts +8 -0
  234. package/build/modern/useQuery.d.ts +8 -0
  235. package/build/modern/useQuery.js +12 -0
  236. package/build/modern/useQuery.js.map +1 -0
  237. package/build/modern/useSuspenseInfiniteQuery.cjs +46 -0
  238. package/build/modern/useSuspenseInfiniteQuery.cjs.map +1 -0
  239. package/build/modern/useSuspenseInfiniteQuery.d.cts +6 -0
  240. package/build/modern/useSuspenseInfiniteQuery.d.ts +6 -0
  241. package/build/modern/useSuspenseInfiniteQuery.js +22 -0
  242. package/build/modern/useSuspenseInfiniteQuery.js.map +1 -0
  243. package/build/modern/useSuspenseQuery.cjs +45 -0
  244. package/build/modern/useSuspenseQuery.cjs.map +1 -0
  245. package/build/modern/useSuspenseQuery.d.cts +6 -0
  246. package/build/modern/useSuspenseQuery.d.ts +6 -0
  247. package/build/modern/useSuspenseQuery.js +21 -0
  248. package/build/modern/useSuspenseQuery.js.map +1 -0
  249. package/build/modern/utils.cjs +36 -0
  250. package/build/modern/utils.cjs.map +1 -0
  251. package/build/modern/utils.d.cts +3 -0
  252. package/build/modern/utils.d.ts +3 -0
  253. package/build/modern/utils.js +11 -0
  254. package/build/modern/utils.js.map +1 -0
  255. package/package.json +29 -17
  256. package/src/HydrationBoundary.tsx +1 -1
  257. package/src/__tests__/HydrationBoundary.test.tsx +5 -5
  258. package/src/__tests__/QueryClientProvider.test.tsx +2 -2
  259. package/src/__tests__/QueryResetErrorBoundary.test.tsx +753 -621
  260. package/src/__tests__/ssr-hydration.test.tsx +4 -4
  261. package/src/__tests__/ssr.test.tsx +2 -2
  262. package/src/__tests__/suspense.test.tsx +8 -90
  263. package/src/__tests__/useInfiniteQuery.test.tsx +36 -74
  264. package/src/__tests__/useInfiniteQuery.type.test.tsx +2 -29
  265. package/src/__tests__/useIsFetching.test.tsx +1 -1
  266. package/src/__tests__/useMutation.test.tsx +22 -23
  267. package/src/__tests__/useMutationState.test.tsx +23 -0
  268. package/src/__tests__/useQueries.test.tsx +214 -91
  269. package/src/__tests__/useQuery.test.tsx +691 -551
  270. package/src/__tests__/useQuery.types.test.tsx +22 -1
  271. package/src/__tests__/utils.tsx +11 -5
  272. package/src/errorBoundaryUtils.ts +7 -7
  273. package/src/index.ts +4 -0
  274. package/src/infiniteQueryOptions.ts +93 -0
  275. package/src/queryOptions.ts +42 -0
  276. package/src/suspense.ts +9 -15
  277. package/src/types.ts +50 -8
  278. package/src/useBaseQuery.ts +14 -26
  279. package/src/useInfiniteQuery.ts +50 -7
  280. package/src/useIsFetching.ts +1 -1
  281. package/src/useMutation.ts +4 -4
  282. package/src/useMutationState.ts +8 -8
  283. package/src/useQueries.ts +53 -36
  284. package/src/useQuery.ts +6 -21
  285. package/src/useSuspenseInfiniteQuery.ts +47 -0
  286. package/src/useSuspenseQuery.ts +26 -0
  287. package/build/lib/HydrationBoundary.d.ts +0 -9
  288. package/build/lib/HydrationBoundary.esm.js +0 -29
  289. package/build/lib/HydrationBoundary.esm.js.map +0 -1
  290. package/build/lib/HydrationBoundary.js +0 -50
  291. package/build/lib/HydrationBoundary.js.map +0 -1
  292. package/build/lib/HydrationBoundary.mjs +0 -29
  293. package/build/lib/HydrationBoundary.mjs.map +0 -1
  294. package/build/lib/QueryClientProvider.d.ts +0 -9
  295. package/build/lib/QueryClientProvider.esm.js +0 -31
  296. package/build/lib/QueryClientProvider.esm.js.map +0 -1
  297. package/build/lib/QueryClientProvider.js +0 -54
  298. package/build/lib/QueryClientProvider.js.map +0 -1
  299. package/build/lib/QueryClientProvider.mjs +0 -31
  300. package/build/lib/QueryClientProvider.mjs.map +0 -1
  301. package/build/lib/QueryErrorResetBoundary.d.ts +0 -11
  302. package/build/lib/QueryErrorResetBoundary.esm.js +0 -38
  303. package/build/lib/QueryErrorResetBoundary.esm.js.map +0 -1
  304. package/build/lib/QueryErrorResetBoundary.js +0 -60
  305. package/build/lib/QueryErrorResetBoundary.js.map +0 -1
  306. package/build/lib/QueryErrorResetBoundary.mjs +0 -38
  307. package/build/lib/QueryErrorResetBoundary.mjs.map +0 -1
  308. package/build/lib/__tests__/HydrationBoundary.test.d.ts +0 -1
  309. package/build/lib/__tests__/QueryClientProvider.test.d.ts +0 -1
  310. package/build/lib/__tests__/QueryResetErrorBoundary.test.d.ts +0 -6
  311. package/build/lib/__tests__/ssr-hydration.test.d.ts +0 -1
  312. package/build/lib/__tests__/ssr.test.d.ts +0 -1
  313. package/build/lib/__tests__/suspense.test.d.ts +0 -1
  314. package/build/lib/__tests__/useInfiniteQuery.test.d.ts +0 -1
  315. package/build/lib/__tests__/useInfiniteQuery.type.test.d.ts +0 -1
  316. package/build/lib/__tests__/useIsFetching.test.d.ts +0 -1
  317. package/build/lib/__tests__/useMutation.test.d.ts +0 -1
  318. package/build/lib/__tests__/useMutationState.test.d.ts +0 -1
  319. package/build/lib/__tests__/useQueries.test.d.ts +0 -1
  320. package/build/lib/__tests__/useQuery.test.d.ts +0 -1
  321. package/build/lib/__tests__/useQuery.types.test.d.ts +0 -1
  322. package/build/lib/__tests__/utils.d.ts +0 -28
  323. package/build/lib/errorBoundaryUtils.d.ts +0 -10
  324. package/build/lib/errorBoundaryUtils.esm.js +0 -28
  325. package/build/lib/errorBoundaryUtils.esm.js.map +0 -1
  326. package/build/lib/errorBoundaryUtils.js +0 -51
  327. package/build/lib/errorBoundaryUtils.js.map +0 -1
  328. package/build/lib/errorBoundaryUtils.mjs +0 -28
  329. package/build/lib/errorBoundaryUtils.mjs.map +0 -1
  330. package/build/lib/index.d.ts +0 -16
  331. package/build/lib/index.esm.js +0 -12
  332. package/build/lib/index.esm.js.map +0 -1
  333. package/build/lib/index.js +0 -38
  334. package/build/lib/index.js.map +0 -1
  335. package/build/lib/index.mjs +0 -12
  336. package/build/lib/index.mjs.map +0 -1
  337. package/build/lib/isRestoring.d.ts +0 -3
  338. package/build/lib/isRestoring.esm.js +0 -9
  339. package/build/lib/isRestoring.esm.js.map +0 -1
  340. package/build/lib/isRestoring.js +0 -31
  341. package/build/lib/isRestoring.js.map +0 -1
  342. package/build/lib/isRestoring.mjs +0 -9
  343. package/build/lib/isRestoring.mjs.map +0 -1
  344. package/build/lib/suspense.d.ts +0 -9
  345. package/build/lib/suspense.esm.js +0 -24
  346. package/build/lib/suspense.esm.js.map +0 -1
  347. package/build/lib/suspense.js +0 -29
  348. package/build/lib/suspense.js.map +0 -1
  349. package/build/lib/suspense.mjs +0 -24
  350. package/build/lib/suspense.mjs.map +0 -1
  351. package/build/lib/types.d.ts +0 -26
  352. package/build/lib/useBaseQuery.d.ts +0 -3
  353. package/build/lib/useBaseQuery.esm.js +0 -63
  354. package/build/lib/useBaseQuery.esm.js.map +0 -1
  355. package/build/lib/useBaseQuery.js +0 -84
  356. package/build/lib/useBaseQuery.js.map +0 -1
  357. package/build/lib/useBaseQuery.mjs +0 -63
  358. package/build/lib/useBaseQuery.mjs.map +0 -1
  359. package/build/lib/useInfiniteQuery.d.ts +0 -3
  360. package/build/lib/useInfiniteQuery.esm.js +0 -13
  361. package/build/lib/useInfiniteQuery.esm.js.map +0 -1
  362. package/build/lib/useInfiniteQuery.js +0 -15
  363. package/build/lib/useInfiniteQuery.js.map +0 -1
  364. package/build/lib/useInfiniteQuery.mjs +0 -13
  365. package/build/lib/useInfiniteQuery.mjs.map +0 -1
  366. package/build/lib/useIsFetching.d.ts +0 -2
  367. package/build/lib/useIsFetching.esm.js +0 -13
  368. package/build/lib/useIsFetching.esm.js.map +0 -1
  369. package/build/lib/useIsFetching.js +0 -34
  370. package/build/lib/useIsFetching.js.map +0 -1
  371. package/build/lib/useIsFetching.mjs +0 -13
  372. package/build/lib/useIsFetching.mjs.map +0 -1
  373. package/build/lib/useMutation.d.ts +0 -3
  374. package/build/lib/useMutation.esm.js +0 -33
  375. package/build/lib/useMutation.esm.js.map +0 -1
  376. package/build/lib/useMutation.js +0 -54
  377. package/build/lib/useMutation.js.map +0 -1
  378. package/build/lib/useMutation.mjs +0 -33
  379. package/build/lib/useMutation.mjs.map +0 -1
  380. package/build/lib/useMutationState.d.ts +0 -8
  381. package/build/lib/useMutationState.esm.js +0 -38
  382. package/build/lib/useMutationState.esm.js.map +0 -1
  383. package/build/lib/useMutationState.js +0 -60
  384. package/build/lib/useMutationState.js.map +0 -1
  385. package/build/lib/useMutationState.mjs +0 -38
  386. package/build/lib/useMutationState.mjs.map +0 -1
  387. package/build/lib/useQueries.esm.js +0 -73
  388. package/build/lib/useQueries.esm.js.map +0 -1
  389. package/build/lib/useQueries.js +0 -94
  390. package/build/lib/useQueries.js.map +0 -1
  391. package/build/lib/useQueries.mjs +0 -70
  392. package/build/lib/useQueries.mjs.map +0 -1
  393. package/build/lib/useQuery.d.ts +0 -11
  394. package/build/lib/useQuery.esm.js +0 -12
  395. package/build/lib/useQuery.esm.js.map +0 -1
  396. package/build/lib/useQuery.js +0 -14
  397. package/build/lib/useQuery.js.map +0 -1
  398. package/build/lib/useQuery.mjs +0 -12
  399. package/build/lib/useQuery.mjs.map +0 -1
  400. package/build/lib/utils.d.ts +0 -1
  401. package/build/lib/utils.esm.js +0 -10
  402. package/build/lib/utils.esm.js.map +0 -1
  403. package/build/lib/utils.js +0 -12
  404. package/build/lib/utils.js.map +0 -1
  405. package/build/lib/utils.mjs +0 -10
  406. package/build/lib/utils.mjs.map +0 -1
  407. package/build/umd/index.development.js +0 -3040
  408. package/build/umd/index.development.js.map +0 -1
  409. package/build/umd/index.production.js +0 -2
  410. package/build/umd/index.production.js.map +0 -1
  411. /package/src/{isRestoring.tsx → isRestoring.ts} +0 -0
@@ -1,3040 +0,0 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactQuery = {}, global.React));
5
- })(this, (function (exports, React) { 'use strict';
6
-
7
- function _interopNamespaceDefault(e) {
8
- var n = Object.create(null);
9
- if (e) {
10
- Object.keys(e).forEach(function (k) {
11
- if (k !== 'default') {
12
- var d = Object.getOwnPropertyDescriptor(e, k);
13
- Object.defineProperty(n, k, d.get ? d : {
14
- enumerable: true,
15
- get: function () { return e[k]; }
16
- });
17
- }
18
- });
19
- }
20
- n.default = e;
21
- return Object.freeze(n);
22
- }
23
-
24
- var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
25
-
26
- class Subscribable {
27
- constructor() {
28
- this.listeners = [];
29
- this.subscribe = this.subscribe.bind(this);
30
- }
31
- subscribe(listener) {
32
- this.listeners.push(listener);
33
- this.onSubscribe();
34
- return () => {
35
- this.listeners = this.listeners.filter(x => x !== listener);
36
- this.onUnsubscribe();
37
- };
38
- }
39
- hasListeners() {
40
- return this.listeners.length > 0;
41
- }
42
- onSubscribe() {
43
- // Do nothing
44
- }
45
- onUnsubscribe() {
46
- // Do nothing
47
- }
48
- }
49
-
50
- // TYPES
51
-
52
- // UTILS
53
-
54
- const isServer = typeof window === 'undefined' || 'Deno' in window;
55
- function noop$1() {
56
- return undefined;
57
- }
58
- function functionalUpdate(updater, input) {
59
- return typeof updater === 'function' ? updater(input) : updater;
60
- }
61
- function isValidTimeout(value) {
62
- return typeof value === 'number' && value >= 0 && value !== Infinity;
63
- }
64
- function timeUntilStale(updatedAt, staleTime) {
65
- return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
66
- }
67
- function matchQuery(filters, query) {
68
- const {
69
- type = 'all',
70
- exact,
71
- fetchStatus,
72
- predicate,
73
- queryKey,
74
- stale
75
- } = filters;
76
- if (queryKey) {
77
- if (exact) {
78
- if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
79
- return false;
80
- }
81
- } else if (!partialMatchKey(query.queryKey, queryKey)) {
82
- return false;
83
- }
84
- }
85
- if (type !== 'all') {
86
- const isActive = query.isActive();
87
- if (type === 'active' && !isActive) {
88
- return false;
89
- }
90
- if (type === 'inactive' && isActive) {
91
- return false;
92
- }
93
- }
94
- if (typeof stale === 'boolean' && query.isStale() !== stale) {
95
- return false;
96
- }
97
- if (typeof fetchStatus !== 'undefined' && fetchStatus !== query.state.fetchStatus) {
98
- return false;
99
- }
100
- if (predicate && !predicate(query)) {
101
- return false;
102
- }
103
- return true;
104
- }
105
- function matchMutation(filters, mutation) {
106
- const {
107
- exact,
108
- status,
109
- predicate,
110
- mutationKey
111
- } = filters;
112
- if (mutationKey) {
113
- if (!mutation.options.mutationKey) {
114
- return false;
115
- }
116
- if (exact) {
117
- if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {
118
- return false;
119
- }
120
- } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
121
- return false;
122
- }
123
- }
124
- if (status && mutation.state.status !== status) {
125
- return false;
126
- }
127
- if (predicate && !predicate(mutation)) {
128
- return false;
129
- }
130
- return true;
131
- }
132
- function hashQueryKeyByOptions(queryKey, options) {
133
- const hashFn = options?.queryKeyHashFn || hashKey;
134
- return hashFn(queryKey);
135
- }
136
-
137
- /**
138
- * Default query & mutation keys hash function.
139
- * Hashes the value into a stable hash.
140
- */
141
- function hashKey(queryKey) {
142
- return JSON.stringify(queryKey, (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
143
- result[key] = val[key];
144
- return result;
145
- }, {}) : val);
146
- }
147
-
148
- /**
149
- * Checks if key `b` partially matches with key `a`.
150
- */
151
-
152
- function partialMatchKey(a, b) {
153
- if (a === b) {
154
- return true;
155
- }
156
- if (typeof a !== typeof b) {
157
- return false;
158
- }
159
- if (a && b && typeof a === 'object' && typeof b === 'object') {
160
- return !Object.keys(b).some(key => !partialMatchKey(a[key], b[key]));
161
- }
162
- return false;
163
- }
164
-
165
- /**
166
- * This function returns `a` if `b` is deeply equal.
167
- * If not, it will replace any deeply equal children of `b` with those of `a`.
168
- * This can be used for structural sharing between JSON values for example.
169
- */
170
-
171
- function replaceEqualDeep(a, b) {
172
- if (a === b) {
173
- return a;
174
- }
175
- const array = isPlainArray(a) && isPlainArray(b);
176
- if (array || isPlainObject(a) && isPlainObject(b)) {
177
- const aSize = array ? a.length : Object.keys(a).length;
178
- const bItems = array ? b : Object.keys(b);
179
- const bSize = bItems.length;
180
- const copy = array ? [] : {};
181
- let equalItems = 0;
182
- for (let i = 0; i < bSize; i++) {
183
- const key = array ? i : bItems[i];
184
- copy[key] = replaceEqualDeep(a[key], b[key]);
185
- if (copy[key] === a[key]) {
186
- equalItems++;
187
- }
188
- }
189
- return aSize === bSize && equalItems === aSize ? a : copy;
190
- }
191
- return b;
192
- }
193
-
194
- /**
195
- * Shallow compare objects. Only works with objects that always have the same properties.
196
- */
197
- function shallowEqualObjects(a, b) {
198
- if (a && !b || b && !a) {
199
- return false;
200
- }
201
- for (const key in a) {
202
- if (a[key] !== b[key]) {
203
- return false;
204
- }
205
- }
206
- return true;
207
- }
208
- function isPlainArray(value) {
209
- return Array.isArray(value) && value.length === Object.keys(value).length;
210
- }
211
-
212
- // Copied from: https://github.com/jonschlinkert/is-plain-object
213
- function isPlainObject(o) {
214
- if (!hasObjectPrototype(o)) {
215
- return false;
216
- }
217
-
218
- // If has modified constructor
219
- const ctor = o.constructor;
220
- if (typeof ctor === 'undefined') {
221
- return true;
222
- }
223
-
224
- // If has modified prototype
225
- const prot = ctor.prototype;
226
- if (!hasObjectPrototype(prot)) {
227
- return false;
228
- }
229
-
230
- // If constructor does not have an Object-specific method
231
- if (!prot.hasOwnProperty('isPrototypeOf')) {
232
- return false;
233
- }
234
-
235
- // Most likely a plain Object
236
- return true;
237
- }
238
- function hasObjectPrototype(o) {
239
- return Object.prototype.toString.call(o) === '[object Object]';
240
- }
241
- function sleep(timeout) {
242
- return new Promise(resolve => {
243
- setTimeout(resolve, timeout);
244
- });
245
- }
246
-
247
- /**
248
- * Schedules a microtask.
249
- * This can be useful to schedule state updates after rendering.
250
- */
251
- function scheduleMicrotask(callback) {
252
- sleep(0).then(callback);
253
- }
254
- function replaceData(prevData, data, options) {
255
- if (typeof options.structuralSharing === 'function') {
256
- return options.structuralSharing(prevData, data);
257
- } else if (options.structuralSharing !== false) {
258
- // Structurally share data between prev and new data if needed
259
- return replaceEqualDeep(prevData, data);
260
- }
261
- return data;
262
- }
263
- function keepPreviousData(previousData) {
264
- return previousData;
265
- }
266
- function addToEnd(items, item, max = 0) {
267
- const newItems = [...items, item];
268
- return max && newItems.length > max ? newItems.slice(1) : newItems;
269
- }
270
- function addToStart(items, item, max = 0) {
271
- const newItems = [item, ...items];
272
- return max && newItems.length > max ? newItems.slice(0, -1) : newItems;
273
- }
274
-
275
- class FocusManager extends Subscribable {
276
- #focused;
277
- #cleanup;
278
- #setup;
279
- constructor() {
280
- super();
281
- this.#setup = onFocus => {
282
- // addEventListener does not exist in React Native, but window does
283
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
284
- if (!isServer && window.addEventListener) {
285
- const listener = () => onFocus();
286
- // Listen to visibilitychange
287
- window.addEventListener('visibilitychange', listener, false);
288
- return () => {
289
- // Be sure to unsubscribe if a new handler is set
290
- window.removeEventListener('visibilitychange', listener);
291
- };
292
- }
293
- return;
294
- };
295
- }
296
- onSubscribe() {
297
- if (!this.#cleanup) {
298
- this.setEventListener(this.#setup);
299
- }
300
- }
301
- onUnsubscribe() {
302
- if (!this.hasListeners()) {
303
- this.#cleanup?.();
304
- this.#cleanup = undefined;
305
- }
306
- }
307
- setEventListener(setup) {
308
- this.#setup = setup;
309
- this.#cleanup?.();
310
- this.#cleanup = setup(focused => {
311
- if (typeof focused === 'boolean') {
312
- this.setFocused(focused);
313
- } else {
314
- this.onFocus();
315
- }
316
- });
317
- }
318
- setFocused(focused) {
319
- this.#focused = focused;
320
- if (focused) {
321
- this.onFocus();
322
- }
323
- }
324
- onFocus() {
325
- this.listeners.forEach(listener => {
326
- listener();
327
- });
328
- }
329
- isFocused() {
330
- if (typeof this.#focused === 'boolean') {
331
- return this.#focused;
332
- }
333
-
334
- // document global can be unavailable in react native
335
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
336
- return globalThis.document?.visibilityState !== 'hidden';
337
- }
338
- }
339
- const focusManager = new FocusManager();
340
-
341
- class OnlineManager extends Subscribable {
342
- #online;
343
- #cleanup;
344
- #setup;
345
- constructor() {
346
- super();
347
- this.#setup = onOnline => {
348
- // addEventListener does not exist in React Native, but window does
349
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
350
- if (!isServer && window.addEventListener) {
351
- const listener = () => onOnline();
352
- // Listen to online
353
- window.addEventListener('online', listener, false);
354
- window.addEventListener('offline', listener, false);
355
- return () => {
356
- // Be sure to unsubscribe if a new handler is set
357
- window.removeEventListener('online', listener);
358
- window.removeEventListener('offline', listener);
359
- };
360
- }
361
- return;
362
- };
363
- }
364
- onSubscribe() {
365
- if (!this.#cleanup) {
366
- this.setEventListener(this.#setup);
367
- }
368
- }
369
- onUnsubscribe() {
370
- if (!this.hasListeners()) {
371
- this.#cleanup?.();
372
- this.#cleanup = undefined;
373
- }
374
- }
375
- setEventListener(setup) {
376
- this.#setup = setup;
377
- this.#cleanup?.();
378
- this.#cleanup = setup(online => {
379
- if (typeof online === 'boolean') {
380
- this.setOnline(online);
381
- } else {
382
- this.onOnline();
383
- }
384
- });
385
- }
386
- setOnline(online) {
387
- this.#online = online;
388
- if (online) {
389
- this.onOnline();
390
- }
391
- }
392
- onOnline() {
393
- this.listeners.forEach(listener => {
394
- listener();
395
- });
396
- }
397
- isOnline() {
398
- if (typeof this.#online === 'boolean') {
399
- return this.#online;
400
- }
401
- if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') {
402
- return true;
403
- }
404
- return navigator.onLine;
405
- }
406
- }
407
- const onlineManager = new OnlineManager();
408
-
409
- function defaultRetryDelay(failureCount) {
410
- return Math.min(1000 * 2 ** failureCount, 30000);
411
- }
412
- function canFetch(networkMode) {
413
- return (networkMode ?? 'online') === 'online' ? onlineManager.isOnline() : true;
414
- }
415
- class CancelledError {
416
- constructor(options) {
417
- this.revert = options?.revert;
418
- this.silent = options?.silent;
419
- }
420
- }
421
- function isCancelledError(value) {
422
- return value instanceof CancelledError;
423
- }
424
- function createRetryer(config) {
425
- let isRetryCancelled = false;
426
- let failureCount = 0;
427
- let isResolved = false;
428
- let continueFn;
429
- let promiseResolve;
430
- let promiseReject;
431
- const promise = new Promise((outerResolve, outerReject) => {
432
- promiseResolve = outerResolve;
433
- promiseReject = outerReject;
434
- });
435
- const cancel = cancelOptions => {
436
- if (!isResolved) {
437
- reject(new CancelledError(cancelOptions));
438
- config.abort?.();
439
- }
440
- };
441
- const cancelRetry = () => {
442
- isRetryCancelled = true;
443
- };
444
- const continueRetry = () => {
445
- isRetryCancelled = false;
446
- };
447
- const shouldPause = () => !focusManager.isFocused() || config.networkMode !== 'always' && !onlineManager.isOnline();
448
- const resolve = value => {
449
- if (!isResolved) {
450
- isResolved = true;
451
- config.onSuccess?.(value);
452
- continueFn?.();
453
- promiseResolve(value);
454
- }
455
- };
456
- const reject = value => {
457
- if (!isResolved) {
458
- isResolved = true;
459
- config.onError?.(value);
460
- continueFn?.();
461
- promiseReject(value);
462
- }
463
- };
464
- const pause = () => {
465
- return new Promise(continueResolve => {
466
- continueFn = value => {
467
- const canContinue = isResolved || !shouldPause();
468
- if (canContinue) {
469
- continueResolve(value);
470
- }
471
- return canContinue;
472
- };
473
- config.onPause?.();
474
- }).then(() => {
475
- continueFn = undefined;
476
- if (!isResolved) {
477
- config.onContinue?.();
478
- }
479
- });
480
- };
481
-
482
- // Create loop function
483
- const run = () => {
484
- // Do nothing if already resolved
485
- if (isResolved) {
486
- return;
487
- }
488
- let promiseOrValue;
489
-
490
- // Execute query
491
- try {
492
- promiseOrValue = config.fn();
493
- } catch (error) {
494
- promiseOrValue = Promise.reject(error);
495
- }
496
- Promise.resolve(promiseOrValue).then(resolve).catch(error => {
497
- // Stop if the fetch is already resolved
498
- if (isResolved) {
499
- return;
500
- }
501
-
502
- // Do we need to retry the request?
503
- const retry = config.retry ?? 3;
504
- const retryDelay = config.retryDelay ?? defaultRetryDelay;
505
- const delay = typeof retryDelay === 'function' ? retryDelay(failureCount, error) : retryDelay;
506
- const shouldRetry = retry === true || typeof retry === 'number' && failureCount < retry || typeof retry === 'function' && retry(failureCount, error);
507
- if (isRetryCancelled || !shouldRetry) {
508
- // We are done if the query does not need to be retried
509
- reject(error);
510
- return;
511
- }
512
- failureCount++;
513
-
514
- // Notify on fail
515
- config.onFail?.(failureCount, error);
516
-
517
- // Delay
518
- sleep(delay)
519
- // Pause if the document is not visible or when the device is offline
520
- .then(() => {
521
- if (shouldPause()) {
522
- return pause();
523
- }
524
- return;
525
- }).then(() => {
526
- if (isRetryCancelled) {
527
- reject(error);
528
- } else {
529
- run();
530
- }
531
- });
532
- });
533
- };
534
-
535
- // Start loop
536
- if (canFetch(config.networkMode)) {
537
- run();
538
- } else {
539
- pause().then(run);
540
- }
541
- return {
542
- promise,
543
- cancel,
544
- continue: () => {
545
- const didContinue = continueFn?.();
546
- return didContinue ? promise : Promise.resolve();
547
- },
548
- cancelRetry,
549
- continueRetry
550
- };
551
- }
552
-
553
- // TYPES
554
-
555
- function createNotifyManager() {
556
- let queue = [];
557
- let transactions = 0;
558
- let notifyFn = callback => {
559
- callback();
560
- };
561
- let batchNotifyFn = callback => {
562
- callback();
563
- };
564
- const batch = callback => {
565
- let result;
566
- transactions++;
567
- try {
568
- result = callback();
569
- } finally {
570
- transactions--;
571
- if (!transactions) {
572
- flush();
573
- }
574
- }
575
- return result;
576
- };
577
- const schedule = callback => {
578
- if (transactions) {
579
- queue.push(callback);
580
- } else {
581
- scheduleMicrotask(() => {
582
- notifyFn(callback);
583
- });
584
- }
585
- };
586
-
587
- /**
588
- * All calls to the wrapped function will be batched.
589
- */
590
- const batchCalls = callback => {
591
- return (...args) => {
592
- schedule(() => {
593
- callback(...args);
594
- });
595
- };
596
- };
597
- const flush = () => {
598
- const originalQueue = queue;
599
- queue = [];
600
- if (originalQueue.length) {
601
- scheduleMicrotask(() => {
602
- batchNotifyFn(() => {
603
- originalQueue.forEach(callback => {
604
- notifyFn(callback);
605
- });
606
- });
607
- });
608
- }
609
- };
610
-
611
- /**
612
- * Use this method to set a custom notify function.
613
- * This can be used to for example wrap notifications with `React.act` while running tests.
614
- */
615
- const setNotifyFunction = fn => {
616
- notifyFn = fn;
617
- };
618
-
619
- /**
620
- * Use this method to set a custom function to batch notifications together into a single tick.
621
- * By default React Query will use the batch function provided by ReactDOM or React Native.
622
- */
623
- const setBatchNotifyFunction = fn => {
624
- batchNotifyFn = fn;
625
- };
626
- return {
627
- batch,
628
- batchCalls,
629
- schedule,
630
- setNotifyFunction,
631
- setBatchNotifyFunction
632
- };
633
- }
634
-
635
- // SINGLETON
636
- const notifyManager = createNotifyManager();
637
-
638
- class Removable {
639
- #gcTimeout;
640
- destroy() {
641
- this.clearGcTimeout();
642
- }
643
- scheduleGc() {
644
- this.clearGcTimeout();
645
- if (isValidTimeout(this.gcTime)) {
646
- this.#gcTimeout = setTimeout(() => {
647
- this.optionalRemove();
648
- }, this.gcTime);
649
- }
650
- }
651
- updateGcTime(newGcTime) {
652
- // Default to 5 minutes (Infinity for server-side) if no gcTime is set
653
- this.gcTime = Math.max(this.gcTime || 0, newGcTime ?? (isServer ? Infinity : 5 * 60 * 1000));
654
- }
655
- clearGcTimeout() {
656
- if (this.#gcTimeout) {
657
- clearTimeout(this.#gcTimeout);
658
- this.#gcTimeout = undefined;
659
- }
660
- }
661
- }
662
-
663
- // TYPES
664
-
665
- // CLASS
666
-
667
- class Query extends Removable {
668
- #initialState;
669
- #revertState;
670
- #cache;
671
- #promise;
672
- #retryer;
673
- #observers;
674
- #defaultOptions;
675
- #abortSignalConsumed;
676
- constructor(config) {
677
- super();
678
- this.#abortSignalConsumed = false;
679
- this.#defaultOptions = config.defaultOptions;
680
- this.#setOptions(config.options);
681
- this.#observers = [];
682
- this.#cache = config.cache;
683
- this.queryKey = config.queryKey;
684
- this.queryHash = config.queryHash;
685
- this.#initialState = config.state || getDefaultState$1(this.options);
686
- this.state = this.#initialState;
687
- this.scheduleGc();
688
- }
689
- get meta() {
690
- return this.options.meta;
691
- }
692
- #setOptions(options) {
693
- this.options = {
694
- ...this.#defaultOptions,
695
- ...options
696
- };
697
- this.updateGcTime(this.options.gcTime);
698
- }
699
- optionalRemove() {
700
- if (!this.#observers.length && this.state.fetchStatus === 'idle') {
701
- this.#cache.remove(this);
702
- }
703
- }
704
- setData(newData, options) {
705
- const data = replaceData(this.state.data, newData, this.options);
706
-
707
- // Set data and mark it as cached
708
- this.#dispatch({
709
- data,
710
- type: 'success',
711
- dataUpdatedAt: options?.updatedAt,
712
- manual: options?.manual
713
- });
714
- return data;
715
- }
716
- setState(state, setStateOptions) {
717
- this.#dispatch({
718
- type: 'setState',
719
- state,
720
- setStateOptions
721
- });
722
- }
723
- cancel(options) {
724
- const promise = this.#promise;
725
- this.#retryer?.cancel(options);
726
- return promise ? promise.then(noop$1).catch(noop$1) : Promise.resolve();
727
- }
728
- destroy() {
729
- super.destroy();
730
- this.cancel({
731
- silent: true
732
- });
733
- }
734
- reset() {
735
- this.destroy();
736
- this.setState(this.#initialState);
737
- }
738
- isActive() {
739
- return this.#observers.some(observer => observer.options.enabled !== false);
740
- }
741
- isDisabled() {
742
- return this.getObserversCount() > 0 && !this.isActive();
743
- }
744
- isStale() {
745
- return this.state.isInvalidated || !this.state.dataUpdatedAt || this.#observers.some(observer => observer.getCurrentResult().isStale);
746
- }
747
- isStaleByTime(staleTime = 0) {
748
- return this.state.isInvalidated || !this.state.dataUpdatedAt || !timeUntilStale(this.state.dataUpdatedAt, staleTime);
749
- }
750
- onFocus() {
751
- const observer = this.#observers.find(x => x.shouldFetchOnWindowFocus());
752
- observer?.refetch({
753
- cancelRefetch: false
754
- });
755
-
756
- // Continue fetch if currently paused
757
- this.#retryer?.continue();
758
- }
759
- onOnline() {
760
- const observer = this.#observers.find(x => x.shouldFetchOnReconnect());
761
- observer?.refetch({
762
- cancelRefetch: false
763
- });
764
-
765
- // Continue fetch if currently paused
766
- this.#retryer?.continue();
767
- }
768
- addObserver(observer) {
769
- if (this.#observers.indexOf(observer) === -1) {
770
- this.#observers.push(observer);
771
-
772
- // Stop the query from being garbage collected
773
- this.clearGcTimeout();
774
- this.#cache.notify({
775
- type: 'observerAdded',
776
- query: this,
777
- observer
778
- });
779
- }
780
- }
781
- removeObserver(observer) {
782
- if (this.#observers.indexOf(observer) !== -1) {
783
- this.#observers = this.#observers.filter(x => x !== observer);
784
- if (!this.#observers.length) {
785
- // If the transport layer does not support cancellation
786
- // we'll let the query continue so the result can be cached
787
- if (this.#retryer) {
788
- if (this.#abortSignalConsumed) {
789
- this.#retryer.cancel({
790
- revert: true
791
- });
792
- } else {
793
- this.#retryer.cancelRetry();
794
- }
795
- }
796
- this.scheduleGc();
797
- }
798
- this.#cache.notify({
799
- type: 'observerRemoved',
800
- query: this,
801
- observer
802
- });
803
- }
804
- }
805
- getObserversCount() {
806
- return this.#observers.length;
807
- }
808
- invalidate() {
809
- if (!this.state.isInvalidated) {
810
- this.#dispatch({
811
- type: 'invalidate'
812
- });
813
- }
814
- }
815
- fetch(options, fetchOptions) {
816
- if (this.state.fetchStatus !== 'idle') {
817
- if (this.state.dataUpdatedAt && fetchOptions?.cancelRefetch) {
818
- // Silently cancel current fetch if the user wants to cancel refetches
819
- this.cancel({
820
- silent: true
821
- });
822
- } else if (this.#promise) {
823
- // make sure that retries that were potentially cancelled due to unmounts can continue
824
- this.#retryer?.continueRetry();
825
- // Return current promise if we are already fetching
826
- return this.#promise;
827
- }
828
- }
829
-
830
- // Update config if passed, otherwise the config from the last execution is used
831
- if (options) {
832
- this.#setOptions(options);
833
- }
834
-
835
- // Use the options from the first observer with a query function if no function is found.
836
- // This can happen when the query is hydrated or created with setQueryData.
837
- if (!this.options.queryFn) {
838
- const observer = this.#observers.find(x => x.options.queryFn);
839
- if (observer) {
840
- this.#setOptions(observer.options);
841
- }
842
- }
843
- {
844
- if (!Array.isArray(this.options.queryKey)) {
845
- console.error(`As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`);
846
- }
847
- }
848
- const abortController = new AbortController();
849
-
850
- // Create query function context
851
- const queryFnContext = {
852
- queryKey: this.queryKey,
853
- meta: this.meta
854
- };
855
-
856
- // Adds an enumerable signal property to the object that
857
- // which sets abortSignalConsumed to true when the signal
858
- // is read.
859
- const addSignalProperty = object => {
860
- Object.defineProperty(object, 'signal', {
861
- enumerable: true,
862
- get: () => {
863
- this.#abortSignalConsumed = true;
864
- return abortController.signal;
865
- }
866
- });
867
- };
868
- addSignalProperty(queryFnContext);
869
-
870
- // Create fetch function
871
- const fetchFn = () => {
872
- if (!this.options.queryFn) {
873
- return Promise.reject(new Error('Missing queryFn'));
874
- }
875
- this.#abortSignalConsumed = false;
876
- return this.options.queryFn(queryFnContext);
877
- };
878
-
879
- // Trigger behavior hook
880
- const context = {
881
- fetchOptions,
882
- options: this.options,
883
- queryKey: this.queryKey,
884
- state: this.state,
885
- fetchFn
886
- };
887
- addSignalProperty(context);
888
- this.options.behavior?.onFetch(context);
889
-
890
- // Store state in case the current fetch needs to be reverted
891
- this.#revertState = this.state;
892
-
893
- // Set to fetching state if not already in it
894
- if (this.state.fetchStatus === 'idle' || this.state.fetchMeta !== context.fetchOptions?.meta) {
895
- this.#dispatch({
896
- type: 'fetch',
897
- meta: context.fetchOptions?.meta
898
- });
899
- }
900
- const onError = error => {
901
- // Optimistically update state if needed
902
- if (!(isCancelledError(error) && error.silent)) {
903
- this.#dispatch({
904
- type: 'error',
905
- error: error
906
- });
907
- }
908
- if (!isCancelledError(error)) {
909
- // Notify cache callback
910
- this.#cache.config.onError?.(error, this);
911
- this.#cache.config.onSettled?.(this.state.data, error, this);
912
- }
913
- if (!this.isFetchingOptimistic) {
914
- // Schedule query gc after fetching
915
- this.scheduleGc();
916
- }
917
- this.isFetchingOptimistic = false;
918
- };
919
-
920
- // Try to fetch the data
921
- this.#retryer = createRetryer({
922
- fn: context.fetchFn,
923
- abort: abortController.abort.bind(abortController),
924
- onSuccess: data => {
925
- if (typeof data === 'undefined') {
926
- {
927
- console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`);
928
- }
929
- onError(new Error('undefined'));
930
- return;
931
- }
932
- this.setData(data);
933
-
934
- // Notify cache callback
935
- this.#cache.config.onSuccess?.(data, this);
936
- this.#cache.config.onSettled?.(data, this.state.error, this);
937
- if (!this.isFetchingOptimistic) {
938
- // Schedule query gc after fetching
939
- this.scheduleGc();
940
- }
941
- this.isFetchingOptimistic = false;
942
- },
943
- onError,
944
- onFail: (failureCount, error) => {
945
- this.#dispatch({
946
- type: 'failed',
947
- failureCount,
948
- error
949
- });
950
- },
951
- onPause: () => {
952
- this.#dispatch({
953
- type: 'pause'
954
- });
955
- },
956
- onContinue: () => {
957
- this.#dispatch({
958
- type: 'continue'
959
- });
960
- },
961
- retry: context.options.retry,
962
- retryDelay: context.options.retryDelay,
963
- networkMode: context.options.networkMode
964
- });
965
- this.#promise = this.#retryer.promise;
966
- return this.#promise;
967
- }
968
- #dispatch(action) {
969
- const reducer = state => {
970
- switch (action.type) {
971
- case 'failed':
972
- return {
973
- ...state,
974
- fetchFailureCount: action.failureCount,
975
- fetchFailureReason: action.error
976
- };
977
- case 'pause':
978
- return {
979
- ...state,
980
- fetchStatus: 'paused'
981
- };
982
- case 'continue':
983
- return {
984
- ...state,
985
- fetchStatus: 'fetching'
986
- };
987
- case 'fetch':
988
- return {
989
- ...state,
990
- fetchFailureCount: 0,
991
- fetchFailureReason: null,
992
- fetchMeta: action.meta ?? null,
993
- fetchStatus: canFetch(this.options.networkMode) ? 'fetching' : 'paused',
994
- ...(!state.dataUpdatedAt && {
995
- error: null,
996
- status: 'pending'
997
- })
998
- };
999
- case 'success':
1000
- return {
1001
- ...state,
1002
- data: action.data,
1003
- dataUpdateCount: state.dataUpdateCount + 1,
1004
- dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),
1005
- error: null,
1006
- isInvalidated: false,
1007
- status: 'success',
1008
- ...(!action.manual && {
1009
- fetchStatus: 'idle',
1010
- fetchFailureCount: 0,
1011
- fetchFailureReason: null
1012
- })
1013
- };
1014
- case 'error':
1015
- const error = action.error;
1016
- if (isCancelledError(error) && error.revert && this.#revertState) {
1017
- return {
1018
- ...this.#revertState
1019
- };
1020
- }
1021
- return {
1022
- ...state,
1023
- error: error,
1024
- errorUpdateCount: state.errorUpdateCount + 1,
1025
- errorUpdatedAt: Date.now(),
1026
- fetchFailureCount: state.fetchFailureCount + 1,
1027
- fetchFailureReason: error,
1028
- fetchStatus: 'idle',
1029
- status: 'error'
1030
- };
1031
- case 'invalidate':
1032
- return {
1033
- ...state,
1034
- isInvalidated: true
1035
- };
1036
- case 'setState':
1037
- return {
1038
- ...state,
1039
- ...action.state
1040
- };
1041
- }
1042
- };
1043
- this.state = reducer(this.state);
1044
- notifyManager.batch(() => {
1045
- this.#observers.forEach(observer => {
1046
- observer.onQueryUpdate(action);
1047
- });
1048
- this.#cache.notify({
1049
- query: this,
1050
- type: 'updated',
1051
- action
1052
- });
1053
- });
1054
- }
1055
- }
1056
- function getDefaultState$1(options) {
1057
- const data = typeof options.initialData === 'function' ? options.initialData() : options.initialData;
1058
- const hasData = typeof data !== 'undefined';
1059
- const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === 'function' ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
1060
- return {
1061
- data,
1062
- dataUpdateCount: 0,
1063
- dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
1064
- error: null,
1065
- errorUpdateCount: 0,
1066
- errorUpdatedAt: 0,
1067
- fetchFailureCount: 0,
1068
- fetchFailureReason: null,
1069
- fetchMeta: null,
1070
- isInvalidated: false,
1071
- status: hasData ? 'success' : 'pending',
1072
- fetchStatus: 'idle'
1073
- };
1074
- }
1075
-
1076
- // CLASS
1077
-
1078
- class QueryCache extends Subscribable {
1079
- #queries;
1080
- constructor(config = {}) {
1081
- super();
1082
- this.config = config;
1083
- this.#queries = config.createStore?.() ?? new Map();
1084
- }
1085
- build(client, options, state) {
1086
- const queryKey = options.queryKey;
1087
- const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);
1088
- let query = this.get(queryHash);
1089
- if (!query) {
1090
- query = new Query({
1091
- cache: this,
1092
- queryKey,
1093
- queryHash,
1094
- options: client.defaultQueryOptions(options),
1095
- state,
1096
- defaultOptions: client.getQueryDefaults(queryKey)
1097
- });
1098
- this.add(query);
1099
- }
1100
- return query;
1101
- }
1102
- add(query) {
1103
- if (!this.#queries.has(query.queryHash)) {
1104
- this.#queries.set(query.queryHash, query);
1105
- this.notify({
1106
- type: 'added',
1107
- query
1108
- });
1109
- }
1110
- }
1111
- remove(query) {
1112
- const queryInMap = this.#queries.get(query.queryHash);
1113
- if (queryInMap) {
1114
- query.destroy();
1115
- if (queryInMap === query) {
1116
- this.#queries.delete(query.queryHash);
1117
- }
1118
- this.notify({
1119
- type: 'removed',
1120
- query
1121
- });
1122
- }
1123
- }
1124
- clear() {
1125
- notifyManager.batch(() => {
1126
- this.getAll().forEach(query => {
1127
- this.remove(query);
1128
- });
1129
- });
1130
- }
1131
- get(queryHash) {
1132
- return this.#queries.get(queryHash);
1133
- }
1134
- getAll() {
1135
- return [...this.#queries.values()];
1136
- }
1137
- find(filters) {
1138
- if (typeof filters.exact === 'undefined') {
1139
- filters.exact = true;
1140
- }
1141
- return this.getAll().find(query => matchQuery(filters, query));
1142
- }
1143
- findAll(filters = {}) {
1144
- const queries = this.getAll();
1145
- return Object.keys(filters).length > 0 ? queries.filter(query => matchQuery(filters, query)) : queries;
1146
- }
1147
- notify(event) {
1148
- notifyManager.batch(() => {
1149
- this.listeners.forEach(listener => {
1150
- listener(event);
1151
- });
1152
- });
1153
- }
1154
- onFocus() {
1155
- notifyManager.batch(() => {
1156
- this.getAll().forEach(query => {
1157
- query.onFocus();
1158
- });
1159
- });
1160
- }
1161
- onOnline() {
1162
- notifyManager.batch(() => {
1163
- this.getAll().forEach(query => {
1164
- query.onOnline();
1165
- });
1166
- });
1167
- }
1168
- }
1169
-
1170
- // TYPES
1171
-
1172
- // CLASS
1173
-
1174
- class Mutation extends Removable {
1175
- #observers;
1176
- #defaultOptions;
1177
- #mutationCache;
1178
- #retryer;
1179
- constructor(config) {
1180
- super();
1181
- this.mutationId = config.mutationId;
1182
- this.#defaultOptions = config.defaultOptions;
1183
- this.#mutationCache = config.mutationCache;
1184
- this.#observers = [];
1185
- this.state = config.state || getDefaultState();
1186
- this.setOptions(config.options);
1187
- this.scheduleGc();
1188
- }
1189
- setOptions(options) {
1190
- this.options = {
1191
- ...this.#defaultOptions,
1192
- ...options
1193
- };
1194
- this.updateGcTime(this.options.gcTime);
1195
- }
1196
- get meta() {
1197
- return this.options.meta;
1198
- }
1199
- addObserver(observer) {
1200
- if (this.#observers.indexOf(observer) === -1) {
1201
- this.#observers.push(observer);
1202
-
1203
- // Stop the mutation from being garbage collected
1204
- this.clearGcTimeout();
1205
- this.#mutationCache.notify({
1206
- type: 'observerAdded',
1207
- mutation: this,
1208
- observer
1209
- });
1210
- }
1211
- }
1212
- removeObserver(observer) {
1213
- this.#observers = this.#observers.filter(x => x !== observer);
1214
- this.scheduleGc();
1215
- this.#mutationCache.notify({
1216
- type: 'observerRemoved',
1217
- mutation: this,
1218
- observer
1219
- });
1220
- }
1221
- optionalRemove() {
1222
- if (!this.#observers.length) {
1223
- if (this.state.status === 'pending') {
1224
- this.scheduleGc();
1225
- } else {
1226
- this.#mutationCache.remove(this);
1227
- }
1228
- }
1229
- }
1230
- continue() {
1231
- return this.#retryer?.continue() ??
1232
- // continuing a mutation assumes that variables are set, mutation must have been dehydrated before
1233
- this.execute(this.state.variables);
1234
- }
1235
- async execute(variables) {
1236
- const executeMutation = () => {
1237
- this.#retryer = createRetryer({
1238
- fn: () => {
1239
- if (!this.options.mutationFn) {
1240
- return Promise.reject(new Error('No mutationFn found'));
1241
- }
1242
- return this.options.mutationFn(variables);
1243
- },
1244
- onFail: (failureCount, error) => {
1245
- this.#dispatch({
1246
- type: 'failed',
1247
- failureCount,
1248
- error
1249
- });
1250
- },
1251
- onPause: () => {
1252
- this.#dispatch({
1253
- type: 'pause'
1254
- });
1255
- },
1256
- onContinue: () => {
1257
- this.#dispatch({
1258
- type: 'continue'
1259
- });
1260
- },
1261
- retry: this.options.retry ?? 0,
1262
- retryDelay: this.options.retryDelay,
1263
- networkMode: this.options.networkMode
1264
- });
1265
- return this.#retryer.promise;
1266
- };
1267
- const restored = this.state.status === 'pending';
1268
- try {
1269
- if (!restored) {
1270
- this.#dispatch({
1271
- type: 'pending',
1272
- variables
1273
- });
1274
- // Notify cache callback
1275
- await this.#mutationCache.config.onMutate?.(variables, this);
1276
- const context = await this.options.onMutate?.(variables);
1277
- if (context !== this.state.context) {
1278
- this.#dispatch({
1279
- type: 'pending',
1280
- context,
1281
- variables
1282
- });
1283
- }
1284
- }
1285
- const data = await executeMutation();
1286
-
1287
- // Notify cache callback
1288
- await this.#mutationCache.config.onSuccess?.(data, variables, this.state.context, this);
1289
- await this.options.onSuccess?.(data, variables, this.state.context);
1290
-
1291
- // Notify cache callback
1292
- await this.#mutationCache.config.onSettled?.(data, null, this.state.variables, this.state.context, this);
1293
- await this.options.onSettled?.(data, null, variables, this.state.context);
1294
- this.#dispatch({
1295
- type: 'success',
1296
- data
1297
- });
1298
- return data;
1299
- } catch (error) {
1300
- try {
1301
- // Notify cache callback
1302
- await this.#mutationCache.config.onError?.(error, variables, this.state.context, this);
1303
- await this.options.onError?.(error, variables, this.state.context);
1304
-
1305
- // Notify cache callback
1306
- await this.#mutationCache.config.onSettled?.(undefined, error, this.state.variables, this.state.context, this);
1307
- await this.options.onSettled?.(undefined, error, variables, this.state.context);
1308
- throw error;
1309
- } finally {
1310
- this.#dispatch({
1311
- type: 'error',
1312
- error: error
1313
- });
1314
- }
1315
- }
1316
- }
1317
- #dispatch(action) {
1318
- const reducer = state => {
1319
- switch (action.type) {
1320
- case 'failed':
1321
- return {
1322
- ...state,
1323
- failureCount: action.failureCount,
1324
- failureReason: action.error
1325
- };
1326
- case 'pause':
1327
- return {
1328
- ...state,
1329
- isPaused: true
1330
- };
1331
- case 'continue':
1332
- return {
1333
- ...state,
1334
- isPaused: false
1335
- };
1336
- case 'pending':
1337
- return {
1338
- ...state,
1339
- context: action.context,
1340
- data: undefined,
1341
- failureCount: 0,
1342
- failureReason: null,
1343
- error: null,
1344
- isPaused: !canFetch(this.options.networkMode),
1345
- status: 'pending',
1346
- variables: action.variables,
1347
- submittedAt: Date.now()
1348
- };
1349
- case 'success':
1350
- return {
1351
- ...state,
1352
- data: action.data,
1353
- failureCount: 0,
1354
- failureReason: null,
1355
- error: null,
1356
- status: 'success',
1357
- isPaused: false
1358
- };
1359
- case 'error':
1360
- return {
1361
- ...state,
1362
- data: undefined,
1363
- error: action.error,
1364
- failureCount: state.failureCount + 1,
1365
- failureReason: action.error,
1366
- isPaused: false,
1367
- status: 'error'
1368
- };
1369
- }
1370
- };
1371
- this.state = reducer(this.state);
1372
- notifyManager.batch(() => {
1373
- this.#observers.forEach(observer => {
1374
- observer.onMutationUpdate(action);
1375
- });
1376
- this.#mutationCache.notify({
1377
- mutation: this,
1378
- type: 'updated',
1379
- action
1380
- });
1381
- });
1382
- }
1383
- }
1384
- function getDefaultState() {
1385
- return {
1386
- context: undefined,
1387
- data: undefined,
1388
- error: null,
1389
- failureCount: 0,
1390
- failureReason: null,
1391
- isPaused: false,
1392
- status: 'idle',
1393
- variables: undefined,
1394
- submittedAt: 0
1395
- };
1396
- }
1397
-
1398
- // TYPES
1399
-
1400
- // CLASS
1401
-
1402
- class MutationCache extends Subscribable {
1403
- #mutations;
1404
- #mutationId;
1405
- #resuming;
1406
- constructor(config = {}) {
1407
- super();
1408
- this.config = config;
1409
- this.#mutations = [];
1410
- this.#mutationId = 0;
1411
- }
1412
- build(client, options, state) {
1413
- const mutation = new Mutation({
1414
- mutationCache: this,
1415
- mutationId: ++this.#mutationId,
1416
- options: client.defaultMutationOptions(options),
1417
- state
1418
- });
1419
- this.add(mutation);
1420
- return mutation;
1421
- }
1422
- add(mutation) {
1423
- this.#mutations.push(mutation);
1424
- this.notify({
1425
- type: 'added',
1426
- mutation
1427
- });
1428
- }
1429
- remove(mutation) {
1430
- this.#mutations = this.#mutations.filter(x => x !== mutation);
1431
- this.notify({
1432
- type: 'removed',
1433
- mutation
1434
- });
1435
- }
1436
- clear() {
1437
- notifyManager.batch(() => {
1438
- this.#mutations.forEach(mutation => {
1439
- this.remove(mutation);
1440
- });
1441
- });
1442
- }
1443
- getAll() {
1444
- return this.#mutations;
1445
- }
1446
- find(filters) {
1447
- if (typeof filters.exact === 'undefined') {
1448
- filters.exact = true;
1449
- }
1450
- return this.#mutations.find(mutation => matchMutation(filters, mutation));
1451
- }
1452
- findAll(filters = {}) {
1453
- return this.#mutations.filter(mutation => matchMutation(filters, mutation));
1454
- }
1455
- notify(event) {
1456
- notifyManager.batch(() => {
1457
- this.listeners.forEach(listener => {
1458
- listener(event);
1459
- });
1460
- });
1461
- }
1462
- resumePausedMutations() {
1463
- this.#resuming = (this.#resuming ?? Promise.resolve()).then(() => {
1464
- const pausedMutations = this.#mutations.filter(x => x.state.isPaused);
1465
- return notifyManager.batch(() => pausedMutations.reduce((promise, mutation) => promise.then(() => mutation.continue().catch(noop$1)), Promise.resolve()));
1466
- }).then(() => {
1467
- this.#resuming = undefined;
1468
- });
1469
- return this.#resuming;
1470
- }
1471
- }
1472
-
1473
- function infiniteQueryBehavior() {
1474
- return {
1475
- onFetch: context => {
1476
- context.fetchFn = async () => {
1477
- const options = context.options;
1478
- const direction = context.fetchOptions?.meta?.fetchMore?.direction;
1479
- const oldPages = context.state.data?.pages || [];
1480
- const oldPageParams = context.state.data?.pageParams || [];
1481
- const empty = {
1482
- pages: [],
1483
- pageParams: []
1484
- };
1485
- let cancelled = false;
1486
- const addSignalProperty = object => {
1487
- Object.defineProperty(object, 'signal', {
1488
- enumerable: true,
1489
- get: () => {
1490
- if (context.signal.aborted) {
1491
- cancelled = true;
1492
- } else {
1493
- context.signal.addEventListener('abort', () => {
1494
- cancelled = true;
1495
- });
1496
- }
1497
- return context.signal;
1498
- }
1499
- });
1500
- };
1501
-
1502
- // Get query function
1503
- const queryFn = context.options.queryFn || (() => Promise.reject(new Error('Missing queryFn')));
1504
-
1505
- // Create function to fetch a page
1506
- const fetchPage = async (data, param, previous) => {
1507
- if (cancelled) {
1508
- return Promise.reject();
1509
- }
1510
- if (typeof param === 'undefined' && data.pages.length) {
1511
- return Promise.resolve(data);
1512
- }
1513
- const queryFnContext = {
1514
- queryKey: context.queryKey,
1515
- pageParam: param,
1516
- direction: previous ? 'backward' : 'forward',
1517
- meta: context.options.meta
1518
- };
1519
- addSignalProperty(queryFnContext);
1520
- const page = await queryFn(queryFnContext);
1521
- const {
1522
- maxPages
1523
- } = context.options;
1524
- const addTo = previous ? addToStart : addToEnd;
1525
- return {
1526
- pages: addTo(data.pages, page, maxPages),
1527
- pageParams: addTo(data.pageParams, param, maxPages)
1528
- };
1529
- };
1530
- let result;
1531
-
1532
- // Fetch first page?
1533
- if (!oldPages.length) {
1534
- result = await fetchPage(empty, options.defaultPageParam);
1535
- }
1536
-
1537
- // fetch next / previous page?
1538
- else if (direction) {
1539
- const previous = direction === 'backward';
1540
- const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
1541
- const oldData = {
1542
- pages: oldPages,
1543
- pageParams: oldPageParams
1544
- };
1545
- const param = pageParamFn(options, oldData);
1546
- result = await fetchPage(oldData, param, previous);
1547
- }
1548
-
1549
- // Refetch pages
1550
- else {
1551
- // Fetch first page
1552
- result = await fetchPage(empty, oldPageParams[0]);
1553
-
1554
- // Fetch remaining pages
1555
- for (let i = 1; i < oldPages.length; i++) {
1556
- const param = getNextPageParam(options, result);
1557
- result = await fetchPage(result, param);
1558
- }
1559
- }
1560
- return result;
1561
- };
1562
- }
1563
- };
1564
- }
1565
- function getNextPageParam(options, {
1566
- pages,
1567
- pageParams
1568
- }) {
1569
- const lastIndex = pages.length - 1;
1570
- return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams);
1571
- }
1572
- function getPreviousPageParam(options, {
1573
- pages,
1574
- pageParams
1575
- }) {
1576
- return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams);
1577
- }
1578
-
1579
- /**
1580
- * Checks if there is a next page.
1581
- */
1582
- function hasNextPage(options, data) {
1583
- if (!data) return false;
1584
- return typeof getNextPageParam(options, data) !== 'undefined';
1585
- }
1586
-
1587
- /**
1588
- * Checks if there is a previous page.
1589
- */
1590
- function hasPreviousPage(options, data) {
1591
- if (!data || !options.getPreviousPageParam) return false;
1592
- return typeof getPreviousPageParam(options, data) !== 'undefined';
1593
- }
1594
-
1595
- // CLASS
1596
-
1597
- class QueryClient {
1598
- #queryCache;
1599
- #mutationCache;
1600
- #defaultOptions;
1601
- #queryDefaults;
1602
- #mutationDefaults;
1603
- #mountCount;
1604
- #unsubscribeFocus;
1605
- #unsubscribeOnline;
1606
- constructor(config = {}) {
1607
- this.#queryCache = config.queryCache || new QueryCache();
1608
- this.#mutationCache = config.mutationCache || new MutationCache();
1609
- this.#defaultOptions = config.defaultOptions || {};
1610
- this.#queryDefaults = new Map();
1611
- this.#mutationDefaults = new Map();
1612
- this.#mountCount = 0;
1613
- }
1614
- mount() {
1615
- this.#mountCount++;
1616
- if (this.#mountCount !== 1) return;
1617
- this.#unsubscribeFocus = focusManager.subscribe(() => {
1618
- if (focusManager.isFocused()) {
1619
- this.resumePausedMutations();
1620
- this.#queryCache.onFocus();
1621
- }
1622
- });
1623
- this.#unsubscribeOnline = onlineManager.subscribe(() => {
1624
- if (onlineManager.isOnline()) {
1625
- this.resumePausedMutations();
1626
- this.#queryCache.onOnline();
1627
- }
1628
- });
1629
- }
1630
- unmount() {
1631
- this.#mountCount--;
1632
- if (this.#mountCount !== 0) return;
1633
- this.#unsubscribeFocus?.();
1634
- this.#unsubscribeFocus = undefined;
1635
- this.#unsubscribeOnline?.();
1636
- this.#unsubscribeOnline = undefined;
1637
- }
1638
- isFetching(filters) {
1639
- return this.#queryCache.findAll({
1640
- ...filters,
1641
- fetchStatus: 'fetching'
1642
- }).length;
1643
- }
1644
- isMutating(filters) {
1645
- return this.#mutationCache.findAll({
1646
- ...filters,
1647
- status: 'pending'
1648
- }).length;
1649
- }
1650
- getQueryData(queryKey) {
1651
- return this.#queryCache.find({
1652
- queryKey
1653
- })?.state.data;
1654
- }
1655
- ensureQueryData(options) {
1656
- const cachedData = this.getQueryData(options.queryKey);
1657
- return cachedData ? Promise.resolve(cachedData) : this.fetchQuery(options);
1658
- }
1659
- getQueriesData(filters) {
1660
- return this.getQueryCache().findAll(filters).map(({
1661
- queryKey,
1662
- state
1663
- }) => {
1664
- const data = state.data;
1665
- return [queryKey, data];
1666
- });
1667
- }
1668
- setQueryData(queryKey, updater, options) {
1669
- const query = this.#queryCache.find({
1670
- queryKey
1671
- });
1672
- const prevData = query?.state.data;
1673
- const data = functionalUpdate(updater, prevData);
1674
- if (typeof data === 'undefined') {
1675
- return undefined;
1676
- }
1677
- const defaultedOptions = this.defaultQueryOptions({
1678
- queryKey
1679
- });
1680
- return this.#queryCache.build(this, defaultedOptions).setData(data, {
1681
- ...options,
1682
- manual: true
1683
- });
1684
- }
1685
- setQueriesData(filters, updater, options) {
1686
- return notifyManager.batch(() => this.getQueryCache().findAll(filters).map(({
1687
- queryKey
1688
- }) => [queryKey, this.setQueryData(queryKey, updater, options)]));
1689
- }
1690
- getQueryState(queryKey) {
1691
- return this.#queryCache.find({
1692
- queryKey
1693
- })?.state;
1694
- }
1695
- removeQueries(filters) {
1696
- const queryCache = this.#queryCache;
1697
- notifyManager.batch(() => {
1698
- queryCache.findAll(filters).forEach(query => {
1699
- queryCache.remove(query);
1700
- });
1701
- });
1702
- }
1703
- resetQueries(filters, options) {
1704
- const queryCache = this.#queryCache;
1705
- const refetchFilters = {
1706
- type: 'active',
1707
- ...filters
1708
- };
1709
- return notifyManager.batch(() => {
1710
- queryCache.findAll(filters).forEach(query => {
1711
- query.reset();
1712
- });
1713
- return this.refetchQueries(refetchFilters, options);
1714
- });
1715
- }
1716
- cancelQueries(filters = {}, cancelOptions = {}) {
1717
- if (typeof cancelOptions.revert === 'undefined') {
1718
- cancelOptions.revert = true;
1719
- }
1720
- const promises = notifyManager.batch(() => this.#queryCache.findAll(filters).map(query => query.cancel(cancelOptions)));
1721
- return Promise.all(promises).then(noop$1).catch(noop$1);
1722
- }
1723
- invalidateQueries(filters = {}, options = {}) {
1724
- return notifyManager.batch(() => {
1725
- this.#queryCache.findAll(filters).forEach(query => {
1726
- query.invalidate();
1727
- });
1728
- if (filters.refetchType === 'none') {
1729
- return Promise.resolve();
1730
- }
1731
- const refetchFilters = {
1732
- ...filters,
1733
- type: filters.refetchType ?? filters.type ?? 'active'
1734
- };
1735
- return this.refetchQueries(refetchFilters, options);
1736
- });
1737
- }
1738
- refetchQueries(filters = {}, options) {
1739
- const promises = notifyManager.batch(() => this.#queryCache.findAll(filters).filter(query => !query.isDisabled()).map(query => query.fetch(undefined, {
1740
- ...options,
1741
- cancelRefetch: options?.cancelRefetch ?? true
1742
- })));
1743
- let promise = Promise.all(promises).then(noop$1);
1744
- if (!options?.throwOnError) {
1745
- promise = promise.catch(noop$1);
1746
- }
1747
- return promise;
1748
- }
1749
- fetchQuery(options) {
1750
- const defaultedOptions = this.defaultQueryOptions(options);
1751
-
1752
- // https://github.com/tannerlinsley/react-query/issues/652
1753
- if (typeof defaultedOptions.retry === 'undefined') {
1754
- defaultedOptions.retry = false;
1755
- }
1756
- const query = this.#queryCache.build(this, defaultedOptions);
1757
- return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
1758
- }
1759
- prefetchQuery(options) {
1760
- return this.fetchQuery(options).then(noop$1).catch(noop$1);
1761
- }
1762
- fetchInfiniteQuery(options) {
1763
- options.behavior = infiniteQueryBehavior();
1764
- return this.fetchQuery(options);
1765
- }
1766
- prefetchInfiniteQuery(options) {
1767
- return this.fetchInfiniteQuery(options).then(noop$1).catch(noop$1);
1768
- }
1769
- resumePausedMutations() {
1770
- return this.#mutationCache.resumePausedMutations();
1771
- }
1772
- getQueryCache() {
1773
- return this.#queryCache;
1774
- }
1775
- getMutationCache() {
1776
- return this.#mutationCache;
1777
- }
1778
- getDefaultOptions() {
1779
- return this.#defaultOptions;
1780
- }
1781
- setDefaultOptions(options) {
1782
- this.#defaultOptions = options;
1783
- }
1784
- setQueryDefaults(queryKey, options) {
1785
- this.#queryDefaults.set(hashKey(queryKey), {
1786
- queryKey,
1787
- defaultOptions: options
1788
- });
1789
- }
1790
- getQueryDefaults(queryKey) {
1791
- const defaults = [...this.#queryDefaults.values()];
1792
- let result = {};
1793
- defaults.forEach(queryDefault => {
1794
- if (partialMatchKey(queryKey, queryDefault.queryKey)) {
1795
- result = {
1796
- ...result,
1797
- ...queryDefault.defaultOptions
1798
- };
1799
- }
1800
- });
1801
- return result;
1802
- }
1803
- setMutationDefaults(mutationKey, options) {
1804
- this.#mutationDefaults.set(hashKey(mutationKey), {
1805
- mutationKey,
1806
- defaultOptions: options
1807
- });
1808
- }
1809
- getMutationDefaults(mutationKey) {
1810
- const defaults = [...this.#mutationDefaults.values()];
1811
- let result = {};
1812
- defaults.forEach(queryDefault => {
1813
- if (partialMatchKey(mutationKey, queryDefault.mutationKey)) {
1814
- result = {
1815
- ...result,
1816
- ...queryDefault.defaultOptions
1817
- };
1818
- }
1819
- });
1820
- return result;
1821
- }
1822
- defaultQueryOptions(options) {
1823
- if (options?._defaulted) {
1824
- return options;
1825
- }
1826
- const defaultedOptions = {
1827
- ...this.#defaultOptions.queries,
1828
- ...(options?.queryKey && this.getQueryDefaults(options.queryKey)),
1829
- ...options,
1830
- _defaulted: true
1831
- };
1832
- if (!defaultedOptions.queryHash) {
1833
- defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions);
1834
- }
1835
-
1836
- // dependent default values
1837
- if (typeof defaultedOptions.refetchOnReconnect === 'undefined') {
1838
- defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== 'always';
1839
- }
1840
- if (typeof defaultedOptions.throwErrors === 'undefined') {
1841
- defaultedOptions.throwErrors = !!defaultedOptions.suspense;
1842
- }
1843
- return defaultedOptions;
1844
- }
1845
- defaultMutationOptions(options) {
1846
- if (options?._defaulted) {
1847
- return options;
1848
- }
1849
- return {
1850
- ...this.#defaultOptions.mutations,
1851
- ...(options?.mutationKey && this.getMutationDefaults(options.mutationKey)),
1852
- ...options,
1853
- _defaulted: true
1854
- };
1855
- }
1856
- clear() {
1857
- this.#queryCache.clear();
1858
- this.#mutationCache.clear();
1859
- }
1860
- }
1861
-
1862
- class QueryObserver extends Subscribable {
1863
- #client;
1864
- #currentQuery = undefined;
1865
- #currentQueryInitialState = undefined;
1866
- #currentResult = undefined;
1867
- #currentResultState;
1868
- #currentResultOptions;
1869
- #previousQueryResult;
1870
- #selectError;
1871
- #selectFn;
1872
- #selectResult;
1873
- #staleTimeoutId;
1874
- #refetchIntervalId;
1875
- #currentRefetchInterval;
1876
- #trackedProps = new Set();
1877
- constructor(client, options) {
1878
- super();
1879
- this.#client = client;
1880
- this.options = options;
1881
- this.#selectError = null;
1882
- this.bindMethods();
1883
- this.setOptions(options);
1884
- }
1885
- bindMethods() {
1886
- this.refetch = this.refetch.bind(this);
1887
- }
1888
- onSubscribe() {
1889
- if (this.listeners.length === 1) {
1890
- this.#currentQuery.addObserver(this);
1891
- if (shouldFetchOnMount(this.#currentQuery, this.options)) {
1892
- this.#executeFetch();
1893
- }
1894
- this.#updateTimers();
1895
- }
1896
- }
1897
- onUnsubscribe() {
1898
- if (!this.listeners.length) {
1899
- this.destroy();
1900
- }
1901
- }
1902
- shouldFetchOnReconnect() {
1903
- return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnReconnect);
1904
- }
1905
- shouldFetchOnWindowFocus() {
1906
- return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnWindowFocus);
1907
- }
1908
- destroy() {
1909
- this.listeners = [];
1910
- this.#clearStaleTimeout();
1911
- this.#clearRefetchInterval();
1912
- this.#currentQuery.removeObserver(this);
1913
- }
1914
- setOptions(options, notifyOptions) {
1915
- const prevOptions = this.options;
1916
- const prevQuery = this.#currentQuery;
1917
- this.options = this.#client.defaultQueryOptions(options);
1918
- if (!shallowEqualObjects(prevOptions, this.options)) {
1919
- this.#client.getQueryCache().notify({
1920
- type: 'observerOptionsUpdated',
1921
- query: this.#currentQuery,
1922
- observer: this
1923
- });
1924
- }
1925
- if (typeof this.options.enabled !== 'undefined' && typeof this.options.enabled !== 'boolean') {
1926
- throw new Error('Expected enabled to be a boolean');
1927
- }
1928
-
1929
- // Keep previous query key if the user does not supply one
1930
- if (!this.options.queryKey) {
1931
- this.options.queryKey = prevOptions.queryKey;
1932
- }
1933
- this.#updateQuery();
1934
- const mounted = this.hasListeners();
1935
-
1936
- // Fetch if there are subscribers
1937
- if (mounted && shouldFetchOptionally(this.#currentQuery, prevQuery, this.options, prevOptions)) {
1938
- this.#executeFetch();
1939
- }
1940
-
1941
- // Update result
1942
- this.#updateResult(notifyOptions);
1943
-
1944
- // Update stale interval if needed
1945
- if (mounted && (this.#currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) {
1946
- this.#updateStaleTimeout();
1947
- }
1948
- const nextRefetchInterval = this.#computeRefetchInterval();
1949
-
1950
- // Update refetch interval if needed
1951
- if (mounted && (this.#currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.#currentRefetchInterval)) {
1952
- this.#updateRefetchInterval(nextRefetchInterval);
1953
- }
1954
- }
1955
- getOptimisticResult(options) {
1956
- const query = this.#client.getQueryCache().build(this.#client, options);
1957
- return this.createResult(query, options);
1958
- }
1959
- getCurrentResult() {
1960
- return this.#currentResult;
1961
- }
1962
- trackResult(result) {
1963
- const trackedResult = {};
1964
- Object.keys(result).forEach(key => {
1965
- Object.defineProperty(trackedResult, key, {
1966
- configurable: false,
1967
- enumerable: true,
1968
- get: () => {
1969
- this.#trackedProps.add(key);
1970
- return result[key];
1971
- }
1972
- });
1973
- });
1974
- return trackedResult;
1975
- }
1976
- getCurrentQuery() {
1977
- return this.#currentQuery;
1978
- }
1979
- refetch({
1980
- ...options
1981
- } = {}) {
1982
- return this.fetch({
1983
- ...options
1984
- });
1985
- }
1986
- fetchOptimistic(options) {
1987
- const defaultedOptions = this.#client.defaultQueryOptions(options);
1988
- const query = this.#client.getQueryCache().build(this.#client, defaultedOptions);
1989
- query.isFetchingOptimistic = true;
1990
- return query.fetch().then(() => this.createResult(query, defaultedOptions));
1991
- }
1992
- fetch(fetchOptions) {
1993
- return this.#executeFetch({
1994
- ...fetchOptions,
1995
- cancelRefetch: fetchOptions.cancelRefetch ?? true
1996
- }).then(() => {
1997
- this.#updateResult();
1998
- return this.#currentResult;
1999
- });
2000
- }
2001
- #executeFetch(fetchOptions) {
2002
- // Make sure we reference the latest query as the current one might have been removed
2003
- this.#updateQuery();
2004
-
2005
- // Fetch
2006
- let promise = this.#currentQuery.fetch(this.options, fetchOptions);
2007
- if (!fetchOptions?.throwOnError) {
2008
- promise = promise.catch(noop$1);
2009
- }
2010
- return promise;
2011
- }
2012
- #updateStaleTimeout() {
2013
- this.#clearStaleTimeout();
2014
- if (isServer || this.#currentResult.isStale || !isValidTimeout(this.options.staleTime)) {
2015
- return;
2016
- }
2017
- const time = timeUntilStale(this.#currentResult.dataUpdatedAt, this.options.staleTime);
2018
-
2019
- // The timeout is sometimes triggered 1 ms before the stale time expiration.
2020
- // To mitigate this issue we always add 1 ms to the timeout.
2021
- const timeout = time + 1;
2022
- this.#staleTimeoutId = setTimeout(() => {
2023
- if (!this.#currentResult.isStale) {
2024
- this.#updateResult();
2025
- }
2026
- }, timeout);
2027
- }
2028
- #computeRefetchInterval() {
2029
- return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(this.#currentResult.data, this.#currentQuery) : this.options.refetchInterval ?? false;
2030
- }
2031
- #updateRefetchInterval(nextInterval) {
2032
- this.#clearRefetchInterval();
2033
- this.#currentRefetchInterval = nextInterval;
2034
- if (isServer || this.options.enabled === false || !isValidTimeout(this.#currentRefetchInterval) || this.#currentRefetchInterval === 0) {
2035
- return;
2036
- }
2037
- this.#refetchIntervalId = setInterval(() => {
2038
- if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
2039
- this.#executeFetch();
2040
- }
2041
- }, this.#currentRefetchInterval);
2042
- }
2043
- #updateTimers() {
2044
- this.#updateStaleTimeout();
2045
- this.#updateRefetchInterval(this.#computeRefetchInterval());
2046
- }
2047
- #clearStaleTimeout() {
2048
- if (this.#staleTimeoutId) {
2049
- clearTimeout(this.#staleTimeoutId);
2050
- this.#staleTimeoutId = undefined;
2051
- }
2052
- }
2053
- #clearRefetchInterval() {
2054
- if (this.#refetchIntervalId) {
2055
- clearInterval(this.#refetchIntervalId);
2056
- this.#refetchIntervalId = undefined;
2057
- }
2058
- }
2059
- createResult(query, options) {
2060
- const prevQuery = this.#currentQuery;
2061
- const prevOptions = this.options;
2062
- const prevResult = this.#currentResult;
2063
- const prevResultState = this.#currentResultState;
2064
- const prevResultOptions = this.#currentResultOptions;
2065
- const queryChange = query !== prevQuery;
2066
- const queryInitialState = queryChange ? query.state : this.#currentQueryInitialState;
2067
- const prevQueryResult = queryChange ? this.#currentResult : this.#previousQueryResult;
2068
- const {
2069
- state
2070
- } = query;
2071
- let {
2072
- error,
2073
- errorUpdatedAt,
2074
- fetchStatus,
2075
- status
2076
- } = state;
2077
- let isPlaceholderData = false;
2078
- let data;
2079
-
2080
- // Optimistically set result in fetching state if needed
2081
- if (options._optimisticResults) {
2082
- const mounted = this.hasListeners();
2083
- const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
2084
- const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
2085
- if (fetchOnMount || fetchOptionally) {
2086
- fetchStatus = canFetch(query.options.networkMode) ? 'fetching' : 'paused';
2087
- if (!state.dataUpdatedAt) {
2088
- status = 'pending';
2089
- }
2090
- }
2091
- if (options._optimisticResults === 'isRestoring') {
2092
- fetchStatus = 'idle';
2093
- }
2094
- }
2095
-
2096
- // Select data if needed
2097
- if (options.select && typeof state.data !== 'undefined') {
2098
- // Memoize select result
2099
- if (prevResult && state.data === prevResultState?.data && options.select === this.#selectFn) {
2100
- data = this.#selectResult;
2101
- } else {
2102
- try {
2103
- this.#selectFn = options.select;
2104
- data = options.select(state.data);
2105
- data = replaceData(prevResult?.data, data, options);
2106
- this.#selectResult = data;
2107
- this.#selectError = null;
2108
- } catch (selectError) {
2109
- this.#selectError = selectError;
2110
- }
2111
- }
2112
- }
2113
- // Use query data
2114
- else {
2115
- data = state.data;
2116
- }
2117
-
2118
- // Show placeholder data if needed
2119
- if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && status === 'pending') {
2120
- let placeholderData;
2121
-
2122
- // Memoize placeholder data
2123
- if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) {
2124
- placeholderData = prevResult.data;
2125
- } else {
2126
- placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData(prevQueryResult?.data) : options.placeholderData;
2127
- if (options.select && typeof placeholderData !== 'undefined') {
2128
- try {
2129
- placeholderData = options.select(placeholderData);
2130
- this.#selectError = null;
2131
- } catch (selectError) {
2132
- this.#selectError = selectError;
2133
- }
2134
- }
2135
- }
2136
- if (typeof placeholderData !== 'undefined') {
2137
- status = 'success';
2138
- data = replaceData(prevResult?.data, placeholderData, options);
2139
- isPlaceholderData = true;
2140
- }
2141
- }
2142
- if (this.#selectError) {
2143
- error = this.#selectError;
2144
- data = this.#selectResult;
2145
- errorUpdatedAt = Date.now();
2146
- status = 'error';
2147
- }
2148
- const isFetching = fetchStatus === 'fetching';
2149
- const isPending = status === 'pending';
2150
- const isError = status === 'error';
2151
- const isLoading = isPending && isFetching;
2152
- const result = {
2153
- status,
2154
- fetchStatus,
2155
- isPending,
2156
- isSuccess: status === 'success',
2157
- isError,
2158
- isInitialLoading: isLoading,
2159
- isLoading,
2160
- data,
2161
- dataUpdatedAt: state.dataUpdatedAt,
2162
- error,
2163
- errorUpdatedAt,
2164
- failureCount: state.fetchFailureCount,
2165
- failureReason: state.fetchFailureReason,
2166
- errorUpdateCount: state.errorUpdateCount,
2167
- isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
2168
- isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
2169
- isFetching,
2170
- isRefetching: isFetching && !isPending,
2171
- isLoadingError: isError && state.dataUpdatedAt === 0,
2172
- isPaused: fetchStatus === 'paused',
2173
- isPlaceholderData,
2174
- isRefetchError: isError && state.dataUpdatedAt !== 0,
2175
- isStale: isStale(query, options),
2176
- refetch: this.refetch
2177
- };
2178
- return result;
2179
- }
2180
- #updateResult(notifyOptions) {
2181
- const prevResult = this.#currentResult;
2182
- const nextResult = this.createResult(this.#currentQuery, this.options);
2183
- this.#currentResultState = this.#currentQuery.state;
2184
- this.#currentResultOptions = this.options;
2185
-
2186
- // Only notify and update result if something has changed
2187
- if (shallowEqualObjects(nextResult, prevResult)) {
2188
- return;
2189
- }
2190
- this.#currentResult = nextResult;
2191
-
2192
- // Determine which callbacks to trigger
2193
- const defaultNotifyOptions = {};
2194
- const shouldNotifyListeners = () => {
2195
- if (!prevResult) {
2196
- return true;
2197
- }
2198
- const {
2199
- notifyOnChangeProps
2200
- } = this.options;
2201
- if (notifyOnChangeProps === 'all' || !notifyOnChangeProps && !this.#trackedProps.size) {
2202
- return true;
2203
- }
2204
- const includedProps = new Set(notifyOnChangeProps ?? this.#trackedProps);
2205
- if (this.options.throwErrors) {
2206
- includedProps.add('error');
2207
- }
2208
- return Object.keys(this.#currentResult).some(key => {
2209
- const typedKey = key;
2210
- const changed = this.#currentResult[typedKey] !== prevResult[typedKey];
2211
- return changed && includedProps.has(typedKey);
2212
- });
2213
- };
2214
- if (notifyOptions?.listeners !== false && shouldNotifyListeners()) {
2215
- defaultNotifyOptions.listeners = true;
2216
- }
2217
- this.#notify({
2218
- ...defaultNotifyOptions,
2219
- ...notifyOptions
2220
- });
2221
- }
2222
- #updateQuery() {
2223
- const query = this.#client.getQueryCache().build(this.#client, this.options);
2224
- if (query === this.#currentQuery) {
2225
- return;
2226
- }
2227
- const prevQuery = this.#currentQuery;
2228
- this.#currentQuery = query;
2229
- this.#currentQueryInitialState = query.state;
2230
- this.#previousQueryResult = this.#currentResult;
2231
- if (this.hasListeners()) {
2232
- prevQuery?.removeObserver(this);
2233
- query.addObserver(this);
2234
- }
2235
- }
2236
- onQueryUpdate(action) {
2237
- const notifyOptions = {};
2238
- if (action.type === 'success') {
2239
- notifyOptions.onSuccess = !action.manual;
2240
- } else if (action.type === 'error' && !isCancelledError(action.error)) {
2241
- notifyOptions.onError = true;
2242
- }
2243
- this.#updateResult(notifyOptions);
2244
- if (this.hasListeners()) {
2245
- this.#updateTimers();
2246
- }
2247
- }
2248
- #notify(notifyOptions) {
2249
- notifyManager.batch(() => {
2250
- // First trigger the configuration callbacks
2251
- if (notifyOptions.onSuccess) {
2252
- this.options.onSuccess?.(this.#currentResult.data);
2253
- this.options.onSettled?.(this.#currentResult.data, null);
2254
- } else if (notifyOptions.onError) {
2255
- this.options.onError?.(this.#currentResult.error);
2256
- this.options.onSettled?.(undefined, this.#currentResult.error);
2257
- }
2258
-
2259
- // Then trigger the listeners
2260
- if (notifyOptions.listeners) {
2261
- this.listeners.forEach(listener => {
2262
- listener(this.#currentResult);
2263
- });
2264
- }
2265
-
2266
- // Then the cache listeners
2267
- this.#client.getQueryCache().notify({
2268
- query: this.#currentQuery,
2269
- type: 'observerResultsUpdated'
2270
- });
2271
- });
2272
- }
2273
- }
2274
- function shouldLoadOnMount(query, options) {
2275
- return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false);
2276
- }
2277
- function shouldFetchOnMount(query, options) {
2278
- return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
2279
- }
2280
- function shouldFetchOn(query, options, field) {
2281
- if (options.enabled !== false) {
2282
- const value = typeof field === 'function' ? field(query) : field;
2283
- return value === 'always' || value !== false && isStale(query, options);
2284
- }
2285
- return false;
2286
- }
2287
- function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
2288
- return options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options);
2289
- }
2290
- function isStale(query, options) {
2291
- return query.isStaleByTime(options.staleTime);
2292
- }
2293
-
2294
- function difference(array1, array2) {
2295
- return array1.filter(x => array2.indexOf(x) === -1);
2296
- }
2297
- function replaceAt(array, index, value) {
2298
- const copy = array.slice(0);
2299
- copy[index] = value;
2300
- return copy;
2301
- }
2302
- class QueriesObserver extends Subscribable {
2303
- #client;
2304
- #result;
2305
- #queries;
2306
- #observers;
2307
- constructor(client, queries) {
2308
- super();
2309
- this.#client = client;
2310
- this.#queries = [];
2311
- this.#result = [];
2312
- this.#observers = [];
2313
- if (queries) {
2314
- this.setQueries(queries);
2315
- }
2316
- }
2317
- onSubscribe() {
2318
- if (this.listeners.length === 1) {
2319
- this.#observers.forEach(observer => {
2320
- observer.subscribe(result => {
2321
- this.#onUpdate(observer, result);
2322
- });
2323
- });
2324
- }
2325
- }
2326
- onUnsubscribe() {
2327
- if (!this.listeners.length) {
2328
- this.destroy();
2329
- }
2330
- }
2331
- destroy() {
2332
- this.listeners = [];
2333
- this.#observers.forEach(observer => {
2334
- observer.destroy();
2335
- });
2336
- }
2337
- setQueries(queries, notifyOptions) {
2338
- this.#queries = queries;
2339
- notifyManager.batch(() => {
2340
- const prevObservers = this.#observers;
2341
- const newObserverMatches = this.#findMatchingObservers(this.#queries);
2342
-
2343
- // set options for the new observers to notify of changes
2344
- newObserverMatches.forEach(match => match.observer.setOptions(match.defaultedQueryOptions, notifyOptions));
2345
- const newObservers = newObserverMatches.map(match => match.observer);
2346
- const newResult = newObservers.map(observer => observer.getCurrentResult());
2347
- const hasIndexChange = newObservers.some((observer, index) => observer !== prevObservers[index]);
2348
- if (prevObservers.length === newObservers.length && !hasIndexChange) {
2349
- return;
2350
- }
2351
- this.#observers = newObservers;
2352
- this.#result = newResult;
2353
- if (!this.hasListeners()) {
2354
- return;
2355
- }
2356
- difference(prevObservers, newObservers).forEach(observer => {
2357
- observer.destroy();
2358
- });
2359
- difference(newObservers, prevObservers).forEach(observer => {
2360
- observer.subscribe(result => {
2361
- this.#onUpdate(observer, result);
2362
- });
2363
- });
2364
- this.#notify();
2365
- });
2366
- }
2367
- getCurrentResult() {
2368
- return this.#result;
2369
- }
2370
- getQueries() {
2371
- return this.#observers.map(observer => observer.getCurrentQuery());
2372
- }
2373
- getObservers() {
2374
- return this.#observers;
2375
- }
2376
- getOptimisticResult(queries) {
2377
- return this.#findMatchingObservers(queries).map(match => match.observer.getOptimisticResult(match.defaultedQueryOptions));
2378
- }
2379
- #findMatchingObservers(queries) {
2380
- const prevObservers = this.#observers;
2381
- const defaultedQueryOptions = queries.map(options => this.#client.defaultQueryOptions(options));
2382
- const matchingObservers = defaultedQueryOptions.flatMap(defaultedOptions => {
2383
- const match = prevObservers.find(observer => observer.options.queryHash === defaultedOptions.queryHash);
2384
- if (match != null) {
2385
- return [{
2386
- defaultedQueryOptions: defaultedOptions,
2387
- observer: match
2388
- }];
2389
- }
2390
- return [];
2391
- });
2392
- const matchedQueryHashes = matchingObservers.map(match => match.defaultedQueryOptions.queryHash);
2393
- const unmatchedQueries = defaultedQueryOptions.filter(defaultedOptions => !matchedQueryHashes.includes(defaultedOptions.queryHash));
2394
- const getObserver = options => {
2395
- const defaultedOptions = this.#client.defaultQueryOptions(options);
2396
- const currentObserver = this.#observers.find(o => o.options.queryHash === defaultedOptions.queryHash);
2397
- return currentObserver ?? new QueryObserver(this.#client, defaultedOptions);
2398
- };
2399
- const newOrReusedObservers = unmatchedQueries.map(options => {
2400
- return {
2401
- defaultedQueryOptions: options,
2402
- observer: getObserver(options)
2403
- };
2404
- });
2405
- const sortMatchesByOrderOfQueries = (a, b) => defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions);
2406
- return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries);
2407
- }
2408
- #onUpdate(observer, result) {
2409
- const index = this.#observers.indexOf(observer);
2410
- if (index !== -1) {
2411
- this.#result = replaceAt(this.#result, index, result);
2412
- this.#notify();
2413
- }
2414
- }
2415
- #notify() {
2416
- notifyManager.batch(() => {
2417
- this.listeners.forEach(listener => {
2418
- listener(this.#result);
2419
- });
2420
- });
2421
- }
2422
- }
2423
-
2424
- class InfiniteQueryObserver extends QueryObserver {
2425
- // Type override
2426
-
2427
- // Type override
2428
-
2429
- // Type override
2430
-
2431
- // eslint-disable-next-line @typescript-eslint/no-useless-constructor
2432
- constructor(client, options) {
2433
- super(client, options);
2434
- }
2435
- bindMethods() {
2436
- super.bindMethods();
2437
- this.fetchNextPage = this.fetchNextPage.bind(this);
2438
- this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
2439
- }
2440
- setOptions(options, notifyOptions) {
2441
- super.setOptions({
2442
- ...options,
2443
- behavior: infiniteQueryBehavior()
2444
- }, notifyOptions);
2445
- }
2446
- getOptimisticResult(options) {
2447
- options.behavior = infiniteQueryBehavior();
2448
- return super.getOptimisticResult(options);
2449
- }
2450
- fetchNextPage(options) {
2451
- return this.fetch({
2452
- ...options,
2453
- meta: {
2454
- fetchMore: {
2455
- direction: 'forward'
2456
- }
2457
- }
2458
- });
2459
- }
2460
- fetchPreviousPage(options) {
2461
- return this.fetch({
2462
- ...options,
2463
- meta: {
2464
- fetchMore: {
2465
- direction: 'backward'
2466
- }
2467
- }
2468
- });
2469
- }
2470
- createResult(query, options) {
2471
- const {
2472
- state
2473
- } = query;
2474
- const result = super.createResult(query, options);
2475
- const {
2476
- isFetching,
2477
- isRefetching
2478
- } = result;
2479
- const isFetchingNextPage = isFetching && state.fetchMeta?.fetchMore?.direction === 'forward';
2480
- const isFetchingPreviousPage = isFetching && state.fetchMeta?.fetchMore?.direction === 'backward';
2481
- return {
2482
- ...result,
2483
- fetchNextPage: this.fetchNextPage,
2484
- fetchPreviousPage: this.fetchPreviousPage,
2485
- hasNextPage: hasNextPage(options, state.data),
2486
- hasPreviousPage: hasPreviousPage(options, state.data),
2487
- isFetchingNextPage,
2488
- isFetchingPreviousPage,
2489
- isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage
2490
- };
2491
- }
2492
- }
2493
-
2494
- // TYPES
2495
-
2496
- // CLASS
2497
-
2498
- class MutationObserver extends Subscribable {
2499
- #client;
2500
- #currentResult = undefined;
2501
- #currentMutation;
2502
- #mutateOptions;
2503
- constructor(client, options) {
2504
- super();
2505
- this.#client = client;
2506
- this.setOptions(options);
2507
- this.bindMethods();
2508
- this.#updateResult();
2509
- }
2510
- bindMethods() {
2511
- this.mutate = this.mutate.bind(this);
2512
- this.reset = this.reset.bind(this);
2513
- }
2514
- setOptions(options) {
2515
- const prevOptions = this.options;
2516
- this.options = this.#client.defaultMutationOptions(options);
2517
- if (!shallowEqualObjects(prevOptions, this.options)) {
2518
- this.#client.getMutationCache().notify({
2519
- type: 'observerOptionsUpdated',
2520
- mutation: this.#currentMutation,
2521
- observer: this
2522
- });
2523
- }
2524
- this.#currentMutation?.setOptions(this.options);
2525
- }
2526
- onUnsubscribe() {
2527
- if (!this.listeners.length) {
2528
- this.#currentMutation?.removeObserver(this);
2529
- }
2530
- }
2531
- onMutationUpdate(action) {
2532
- this.#updateResult();
2533
- this.#notify(action);
2534
- }
2535
- getCurrentResult() {
2536
- return this.#currentResult;
2537
- }
2538
- reset() {
2539
- this.#currentMutation = undefined;
2540
- this.#updateResult();
2541
- this.#notify();
2542
- }
2543
- mutate(variables, options) {
2544
- this.#mutateOptions = options;
2545
- this.#currentMutation?.removeObserver(this);
2546
- this.#currentMutation = this.#client.getMutationCache().build(this.#client, this.options);
2547
- this.#currentMutation.addObserver(this);
2548
- return this.#currentMutation.execute(variables);
2549
- }
2550
- #updateResult() {
2551
- const state = this.#currentMutation?.state ?? getDefaultState();
2552
- this.#currentResult = {
2553
- ...state,
2554
- isPending: state.status === 'pending',
2555
- isSuccess: state.status === 'success',
2556
- isError: state.status === 'error',
2557
- isIdle: state.status === 'idle',
2558
- mutate: this.mutate,
2559
- reset: this.reset
2560
- };
2561
- }
2562
- #notify(action) {
2563
- notifyManager.batch(() => {
2564
- // First trigger the mutate callbacks
2565
- if (this.#mutateOptions && this.hasListeners()) {
2566
- if (action?.type === 'success') {
2567
- this.#mutateOptions.onSuccess?.(action.data, this.#currentResult.variables, this.#currentResult.context);
2568
- this.#mutateOptions.onSettled?.(action.data, null, this.#currentResult.variables, this.#currentResult.context);
2569
- } else if (action?.type === 'error') {
2570
- this.#mutateOptions.onError?.(action.error, this.#currentResult.variables, this.#currentResult.context);
2571
- this.#mutateOptions.onSettled?.(undefined, action.error, this.#currentResult.variables, this.#currentResult.context);
2572
- }
2573
- }
2574
-
2575
- // Then trigger the listeners
2576
- this.listeners.forEach(listener => {
2577
- listener(this.#currentResult);
2578
- });
2579
- });
2580
- }
2581
- }
2582
-
2583
- // TYPES
2584
-
2585
- // FUNCTIONS
2586
-
2587
- function dehydrateMutation(mutation) {
2588
- return {
2589
- mutationKey: mutation.options.mutationKey,
2590
- state: mutation.state
2591
- };
2592
- }
2593
-
2594
- // Most config is not dehydrated but instead meant to configure again when
2595
- // consuming the de/rehydrated data, typically with useQuery on the client.
2596
- // Sometimes it might make sense to prefetch data on the server and include
2597
- // in the html-payload, but not consume it on the initial render.
2598
- function dehydrateQuery(query) {
2599
- return {
2600
- state: query.state,
2601
- queryKey: query.queryKey,
2602
- queryHash: query.queryHash
2603
- };
2604
- }
2605
- function defaultShouldDehydrateMutation(mutation) {
2606
- return mutation.state.isPaused;
2607
- }
2608
- function defaultShouldDehydrateQuery(query) {
2609
- return query.state.status === 'success';
2610
- }
2611
- function dehydrate(client, options = {}) {
2612
- const mutations = [];
2613
- const queries = [];
2614
- if (options.dehydrateMutations !== false) {
2615
- const shouldDehydrateMutation = options.shouldDehydrateMutation || defaultShouldDehydrateMutation;
2616
- client.getMutationCache().getAll().forEach(mutation => {
2617
- if (shouldDehydrateMutation(mutation)) {
2618
- mutations.push(dehydrateMutation(mutation));
2619
- }
2620
- });
2621
- }
2622
- if (options.dehydrateQueries !== false) {
2623
- const shouldDehydrateQuery = options.shouldDehydrateQuery || defaultShouldDehydrateQuery;
2624
- client.getQueryCache().getAll().forEach(query => {
2625
- if (shouldDehydrateQuery(query)) {
2626
- queries.push(dehydrateQuery(query));
2627
- }
2628
- });
2629
- }
2630
- return {
2631
- mutations,
2632
- queries
2633
- };
2634
- }
2635
- function hydrate(client, dehydratedState, options) {
2636
- if (typeof dehydratedState !== 'object' || dehydratedState === null) {
2637
- return;
2638
- }
2639
- const mutationCache = client.getMutationCache();
2640
- const queryCache = client.getQueryCache();
2641
-
2642
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2643
- const mutations = dehydratedState.mutations || [];
2644
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2645
- const queries = dehydratedState.queries || [];
2646
- mutations.forEach(dehydratedMutation => {
2647
- mutationCache.build(client, {
2648
- ...options?.defaultOptions?.mutations,
2649
- mutationKey: dehydratedMutation.mutationKey
2650
- }, dehydratedMutation.state);
2651
- });
2652
- queries.forEach(dehydratedQuery => {
2653
- const query = queryCache.get(dehydratedQuery.queryHash);
2654
-
2655
- // Reset fetch status to idle in the dehydrated state to avoid
2656
- // query being stuck in fetching state upon hydration
2657
- const dehydratedQueryState = {
2658
- ...dehydratedQuery.state,
2659
- fetchStatus: 'idle'
2660
- };
2661
-
2662
- // Do not hydrate if an existing query exists with newer data
2663
- if (query) {
2664
- if (query.state.dataUpdatedAt < dehydratedQueryState.dataUpdatedAt) {
2665
- query.setState(dehydratedQueryState);
2666
- }
2667
- return;
2668
- }
2669
-
2670
- // Restore query
2671
- queryCache.build(client, {
2672
- ...options?.defaultOptions?.queries,
2673
- queryKey: dehydratedQuery.queryKey,
2674
- queryHash: dehydratedQuery.queryHash
2675
- }, dehydratedQueryState);
2676
- });
2677
- }
2678
-
2679
- const QueryClientContext = /*#__PURE__*/React__namespace.createContext(undefined);
2680
- const useQueryClient = queryClient => {
2681
- const client = React__namespace.useContext(QueryClientContext);
2682
- if (queryClient) {
2683
- return queryClient;
2684
- }
2685
- if (!client) {
2686
- throw new Error('No QueryClient set, use QueryClientProvider to set one');
2687
- }
2688
- return client;
2689
- };
2690
- const QueryClientProvider = ({
2691
- client,
2692
- children
2693
- }) => {
2694
- React__namespace.useEffect(() => {
2695
- client.mount();
2696
- return () => {
2697
- client.unmount();
2698
- };
2699
- }, [client]);
2700
- return /*#__PURE__*/React__namespace.createElement(QueryClientContext.Provider, {
2701
- value: client
2702
- }, children);
2703
- };
2704
-
2705
- const IsRestoringContext = /*#__PURE__*/React__namespace.createContext(false);
2706
- const useIsRestoring = () => React__namespace.useContext(IsRestoringContext);
2707
- const IsRestoringProvider = IsRestoringContext.Provider;
2708
-
2709
- // CONTEXT
2710
-
2711
- function createValue() {
2712
- let isReset = false;
2713
- return {
2714
- clearReset: () => {
2715
- isReset = false;
2716
- },
2717
- reset: () => {
2718
- isReset = true;
2719
- },
2720
- isReset: () => {
2721
- return isReset;
2722
- }
2723
- };
2724
- }
2725
- const QueryErrorResetBoundaryContext = /*#__PURE__*/React__namespace.createContext(createValue());
2726
-
2727
- // HOOK
2728
-
2729
- const useQueryErrorResetBoundary = () => React__namespace.useContext(QueryErrorResetBoundaryContext);
2730
-
2731
- // COMPONENT
2732
-
2733
- const QueryErrorResetBoundary = ({
2734
- children
2735
- }) => {
2736
- const [value] = React__namespace.useState(() => createValue());
2737
- return /*#__PURE__*/React__namespace.createElement(QueryErrorResetBoundaryContext.Provider, {
2738
- value: value
2739
- }, typeof children === 'function' ? children(value) : children);
2740
- };
2741
-
2742
- function shouldThrowError(throwError, params) {
2743
- // Allow throwError function to override throwing behavior on a per-error basis
2744
- if (typeof throwError === 'function') {
2745
- return throwError(...params);
2746
- }
2747
- return !!throwError;
2748
- }
2749
-
2750
- const ensurePreventErrorBoundaryRetry = (options, errorResetBoundary) => {
2751
- if (options.suspense || options.throwErrors) {
2752
- // Prevent retrying failed query if the error boundary has not been reset yet
2753
- if (!errorResetBoundary.isReset()) {
2754
- options.retryOnMount = false;
2755
- }
2756
- }
2757
- };
2758
- const useClearResetErrorBoundary = errorResetBoundary => {
2759
- React__namespace.useEffect(() => {
2760
- errorResetBoundary.clearReset();
2761
- }, [errorResetBoundary]);
2762
- };
2763
- const getHasError = ({
2764
- result,
2765
- errorResetBoundary,
2766
- throwErrors,
2767
- query
2768
- }) => {
2769
- return result.isError && !errorResetBoundary.isReset() && !result.isFetching && shouldThrowError(throwErrors, [result.error, query]);
2770
- };
2771
-
2772
- const ensureStaleTime = defaultedOptions => {
2773
- if (defaultedOptions.suspense) {
2774
- // Always set stale time when using suspense to prevent
2775
- // fetching again when directly mounting after suspending
2776
- if (typeof defaultedOptions.staleTime !== 'number') {
2777
- defaultedOptions.staleTime = 1000;
2778
- }
2779
- }
2780
- };
2781
- const willFetch = (result, isRestoring) => result.isLoading && result.isFetching && !isRestoring;
2782
- const shouldSuspend = (defaultedOptions, result, isRestoring) => defaultedOptions?.suspense && willFetch(result, isRestoring);
2783
- const fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).then(({
2784
- data
2785
- }) => {
2786
- defaultedOptions.onSuccess?.(data);
2787
- defaultedOptions.onSettled?.(data, null);
2788
- }).catch(error => {
2789
- errorResetBoundary.clearReset();
2790
- defaultedOptions.onError?.(error);
2791
- defaultedOptions.onSettled?.(undefined, error);
2792
- });
2793
-
2794
- // This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.
2795
- // `placeholderData` function does not have a parameter
2796
-
2797
- function useQueries({
2798
- queries
2799
- }, queryClient) {
2800
- const client = useQueryClient(queryClient);
2801
- const isRestoring = useIsRestoring();
2802
- const defaultedQueries = React__namespace.useMemo(() => queries.map(options => {
2803
- const defaultedOptions = client.defaultQueryOptions(options);
2804
-
2805
- // Make sure the results are already in fetching state before subscribing or updating options
2806
- defaultedOptions._optimisticResults = isRestoring ? 'isRestoring' : 'optimistic';
2807
- return defaultedOptions;
2808
- }), [queries, client, isRestoring]);
2809
- const [observer] = React__namespace.useState(() => new QueriesObserver(client, defaultedQueries));
2810
- const optimisticResult = observer.getOptimisticResult(defaultedQueries);
2811
- React__namespace.useSyncExternalStore(React__namespace.useCallback(onStoreChange => isRestoring ? () => undefined : observer.subscribe(notifyManager.batchCalls(onStoreChange)), [observer, isRestoring]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
2812
- React__namespace.useEffect(() => {
2813
- // Do not notify on updates because of changes in the options because
2814
- // these changes should already be reflected in the optimistic result.
2815
- observer.setQueries(defaultedQueries, {
2816
- listeners: false
2817
- });
2818
- }, [defaultedQueries, observer]);
2819
- const errorResetBoundary = useQueryErrorResetBoundary();
2820
- defaultedQueries.forEach(query => {
2821
- ensurePreventErrorBoundaryRetry(query, errorResetBoundary);
2822
- ensureStaleTime(query);
2823
- });
2824
- useClearResetErrorBoundary(errorResetBoundary);
2825
- const shouldAtLeastOneSuspend = optimisticResult.some((result, index) => shouldSuspend(defaultedQueries[index], result, isRestoring));
2826
- const suspensePromises = shouldAtLeastOneSuspend ? optimisticResult.flatMap((result, index) => {
2827
- const options = defaultedQueries[index];
2828
- const queryObserver = observer.getObservers()[index];
2829
- if (options && queryObserver) {
2830
- if (shouldSuspend(options, result, isRestoring)) {
2831
- return fetchOptimistic(options, queryObserver, errorResetBoundary);
2832
- } else if (willFetch(result, isRestoring)) {
2833
- void fetchOptimistic(options, queryObserver, errorResetBoundary);
2834
- }
2835
- }
2836
- return [];
2837
- }) : [];
2838
- if (suspensePromises.length > 0) {
2839
- throw Promise.all(suspensePromises);
2840
- }
2841
- const firstSingleResultWhichShouldThrow = optimisticResult.find((result, index) => getHasError({
2842
- result,
2843
- errorResetBoundary,
2844
- throwErrors: defaultedQueries[index]?.throwErrors ?? false,
2845
- query: observer.getQueries()[index]
2846
- }));
2847
- if (firstSingleResultWhichShouldThrow?.error) {
2848
- throw firstSingleResultWhichShouldThrow.error;
2849
- }
2850
- return optimisticResult;
2851
- }
2852
-
2853
- function useBaseQuery(options, Observer, queryClient) {
2854
- const client = useQueryClient(queryClient);
2855
- const isRestoring = useIsRestoring();
2856
- const errorResetBoundary = useQueryErrorResetBoundary();
2857
- const defaultedOptions = client.defaultQueryOptions(options);
2858
-
2859
- // Make sure results are optimistically set in fetching state before subscribing or updating options
2860
- defaultedOptions._optimisticResults = isRestoring ? 'isRestoring' : 'optimistic';
2861
-
2862
- // Include callbacks in batch renders
2863
- if (defaultedOptions.onError) {
2864
- defaultedOptions.onError = notifyManager.batchCalls(defaultedOptions.onError);
2865
- }
2866
- if (defaultedOptions.onSuccess) {
2867
- defaultedOptions.onSuccess = notifyManager.batchCalls(defaultedOptions.onSuccess);
2868
- }
2869
- if (defaultedOptions.onSettled) {
2870
- defaultedOptions.onSettled = notifyManager.batchCalls(defaultedOptions.onSettled);
2871
- }
2872
- ensureStaleTime(defaultedOptions);
2873
- ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary);
2874
- useClearResetErrorBoundary(errorResetBoundary);
2875
- const [observer] = React__namespace.useState(() => new Observer(client, defaultedOptions));
2876
- const result = observer.getOptimisticResult(defaultedOptions);
2877
- React__namespace.useSyncExternalStore(React__namespace.useCallback(onStoreChange => isRestoring ? () => undefined : observer.subscribe(notifyManager.batchCalls(onStoreChange)), [observer, isRestoring]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
2878
- React__namespace.useEffect(() => {
2879
- // Do not notify on updates because of changes in the options because
2880
- // these changes should already be reflected in the optimistic result.
2881
- observer.setOptions(defaultedOptions, {
2882
- listeners: false
2883
- });
2884
- }, [defaultedOptions, observer]);
2885
-
2886
- // Handle suspense
2887
- if (shouldSuspend(defaultedOptions, result, isRestoring)) {
2888
- throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary);
2889
- }
2890
-
2891
- // Handle error boundary
2892
- if (getHasError({
2893
- result,
2894
- errorResetBoundary,
2895
- throwErrors: defaultedOptions.throwErrors,
2896
- query: observer.getCurrentQuery()
2897
- })) {
2898
- throw result.error;
2899
- }
2900
-
2901
- // Handle result property usage tracking
2902
- return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;
2903
- }
2904
-
2905
- // HOOK
2906
-
2907
- function useQuery(options, queryClient) {
2908
- return useBaseQuery(options, QueryObserver, queryClient);
2909
- }
2910
-
2911
- const HydrationBoundary = ({
2912
- children,
2913
- options = {},
2914
- state,
2915
- queryClient
2916
- }) => {
2917
- const client = useQueryClient(queryClient);
2918
- const optionsRef = React__namespace.useRef(options);
2919
- optionsRef.current = options;
2920
-
2921
- // Running hydrate again with the same queries is safe,
2922
- // it wont overwrite or initialize existing queries,
2923
- // relying on useMemo here is only a performance optimization.
2924
- // hydrate can and should be run *during* render here for SSR to work properly
2925
- React__namespace.useMemo(() => {
2926
- if (state) {
2927
- hydrate(client, state, optionsRef.current);
2928
- }
2929
- }, [client, state]);
2930
- return children;
2931
- };
2932
-
2933
- function useIsFetching(filters, queryClient) {
2934
- const client = useQueryClient(queryClient);
2935
- const queryCache = client.getQueryCache();
2936
- return React__namespace.useSyncExternalStore(React__namespace.useCallback(onStoreChange => queryCache.subscribe(notifyManager.batchCalls(onStoreChange)), [queryCache]), () => client.isFetching(filters), () => client.isFetching(filters));
2937
- }
2938
-
2939
- function useIsMutating(filters, queryClient) {
2940
- const client = useQueryClient(queryClient);
2941
- return useMutationState({
2942
- filters: {
2943
- ...filters,
2944
- status: 'pending'
2945
- }
2946
- }, client).length;
2947
- }
2948
- function getResult(mutationCache, options) {
2949
- return mutationCache.findAll(options.filters).map(mutation => options.select ? options.select(mutation) : mutation.state);
2950
- }
2951
- function useMutationState(options = {}, queryClient) {
2952
- const mutationCache = useQueryClient(queryClient).getMutationCache();
2953
- const optionsRef = React__namespace.useRef(options);
2954
- const result = React__namespace.useRef();
2955
- if (!result.current) {
2956
- result.current = getResult(mutationCache, options);
2957
- }
2958
- React__namespace.useEffect(() => {
2959
- optionsRef.current = options;
2960
- });
2961
- return React__namespace.useSyncExternalStore(React__namespace.useCallback(onStoreChange => mutationCache.subscribe(() => {
2962
- const nextResult = replaceEqualDeep(result.current, getResult(mutationCache, optionsRef.current));
2963
- if (result.current !== nextResult) {
2964
- result.current = nextResult;
2965
- notifyManager.schedule(onStoreChange);
2966
- }
2967
- }), [mutationCache]), () => result.current, () => result.current);
2968
- }
2969
-
2970
- // HOOK
2971
-
2972
- function useMutation(options, queryClient) {
2973
- const client = useQueryClient(queryClient);
2974
- const [observer] = React__namespace.useState(() => new MutationObserver(client, options));
2975
- React__namespace.useEffect(() => {
2976
- observer.setOptions(options);
2977
- }, [observer, options]);
2978
- const result = React__namespace.useSyncExternalStore(React__namespace.useCallback(onStoreChange => observer.subscribe(notifyManager.batchCalls(onStoreChange)), [observer]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
2979
- const mutate = React__namespace.useCallback((variables, mutateOptions) => {
2980
- observer.mutate(variables, mutateOptions).catch(noop);
2981
- }, [observer]);
2982
- if (result.error && shouldThrowError(observer.options.throwErrors, [result.error])) {
2983
- throw result.error;
2984
- }
2985
- return {
2986
- ...result,
2987
- mutate,
2988
- mutateAsync: result.mutate
2989
- };
2990
- }
2991
-
2992
- // eslint-disable-next-line @typescript-eslint/no-empty-function
2993
- function noop() {}
2994
-
2995
- // HOOK
2996
- function useInfiniteQuery(options, queryClient) {
2997
- return useBaseQuery(options,
2998
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
2999
- InfiniteQueryObserver, queryClient);
3000
- }
3001
-
3002
- exports.CancelledError = CancelledError;
3003
- exports.HydrationBoundary = HydrationBoundary;
3004
- exports.InfiniteQueryObserver = InfiniteQueryObserver;
3005
- exports.IsRestoringProvider = IsRestoringProvider;
3006
- exports.MutationCache = MutationCache;
3007
- exports.MutationObserver = MutationObserver;
3008
- exports.QueriesObserver = QueriesObserver;
3009
- exports.QueryCache = QueryCache;
3010
- exports.QueryClient = QueryClient;
3011
- exports.QueryClientContext = QueryClientContext;
3012
- exports.QueryClientProvider = QueryClientProvider;
3013
- exports.QueryErrorResetBoundary = QueryErrorResetBoundary;
3014
- exports.QueryObserver = QueryObserver;
3015
- exports.defaultShouldDehydrateMutation = defaultShouldDehydrateMutation;
3016
- exports.defaultShouldDehydrateQuery = defaultShouldDehydrateQuery;
3017
- exports.dehydrate = dehydrate;
3018
- exports.focusManager = focusManager;
3019
- exports.hashKey = hashKey;
3020
- exports.hydrate = hydrate;
3021
- exports.isCancelledError = isCancelledError;
3022
- exports.isServer = isServer;
3023
- exports.keepPreviousData = keepPreviousData;
3024
- exports.matchQuery = matchQuery;
3025
- exports.notifyManager = notifyManager;
3026
- exports.onlineManager = onlineManager;
3027
- exports.replaceEqualDeep = replaceEqualDeep;
3028
- exports.useInfiniteQuery = useInfiniteQuery;
3029
- exports.useIsFetching = useIsFetching;
3030
- exports.useIsMutating = useIsMutating;
3031
- exports.useIsRestoring = useIsRestoring;
3032
- exports.useMutation = useMutation;
3033
- exports.useMutationState = useMutationState;
3034
- exports.useQueries = useQueries;
3035
- exports.useQuery = useQuery;
3036
- exports.useQueryClient = useQueryClient;
3037
- exports.useQueryErrorResetBoundary = useQueryErrorResetBoundary;
3038
-
3039
- }));
3040
- //# sourceMappingURL=index.development.js.map