@ic-reactor/react 3.13.0 → 4.0.0-beta.2

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 (174) hide show
  1. package/README.md +237 -787
  2. package/dist/index.d.ts +260 -16
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +471 -23
  5. package/dist/index.js.map +1 -1
  6. package/llms.txt +82 -278
  7. package/package.json +11 -39
  8. package/src/index.tsx +612 -0
  9. package/dist/auth/auth-client-compat.d.ts +0 -122
  10. package/dist/auth/auth-client-compat.d.ts.map +0 -1
  11. package/dist/auth/auth-client-compat.js +0 -162
  12. package/dist/auth/auth-client-compat.js.map +0 -1
  13. package/dist/auth/authentication-manager.d.ts +0 -405
  14. package/dist/auth/authentication-manager.d.ts.map +0 -1
  15. package/dist/auth/authentication-manager.js +0 -1537
  16. package/dist/auth/authentication-manager.js.map +0 -1
  17. package/dist/auth/constants.d.ts +0 -24
  18. package/dist/auth/constants.d.ts.map +0 -1
  19. package/dist/auth/constants.js +0 -24
  20. package/dist/auth/constants.js.map +0 -1
  21. package/dist/auth/createIdentityAttributeHooks.d.ts +0 -14
  22. package/dist/auth/createIdentityAttributeHooks.d.ts.map +0 -1
  23. package/dist/auth/createIdentityAttributeHooks.js +0 -122
  24. package/dist/auth/createIdentityAttributeHooks.js.map +0 -1
  25. package/dist/auth/identity-attributes-manager.d.ts +0 -27
  26. package/dist/auth/identity-attributes-manager.d.ts.map +0 -1
  27. package/dist/auth/identity-attributes-manager.js +0 -191
  28. package/dist/auth/identity-attributes-manager.js.map +0 -1
  29. package/dist/auth/identity-attributes.d.ts +0 -19
  30. package/dist/auth/identity-attributes.d.ts.map +0 -1
  31. package/dist/auth/identity-attributes.js +0 -227
  32. package/dist/auth/identity-attributes.js.map +0 -1
  33. package/dist/auth/index.d.ts +0 -8
  34. package/dist/auth/index.d.ts.map +0 -1
  35. package/dist/auth/index.js +0 -8
  36. package/dist/auth/index.js.map +0 -1
  37. package/dist/auth/local-ii-probe.d.ts +0 -57
  38. package/dist/auth/local-ii-probe.d.ts.map +0 -1
  39. package/dist/auth/local-ii-probe.js +0 -121
  40. package/dist/auth/local-ii-probe.js.map +0 -1
  41. package/dist/auth/types.d.ts +0 -222
  42. package/dist/auth/types.d.ts.map +0 -1
  43. package/dist/auth/types.js +0 -2
  44. package/dist/auth/types.js.map +0 -1
  45. package/dist/createActorHooks.d.ts +0 -41
  46. package/dist/createActorHooks.d.ts.map +0 -1
  47. package/dist/createActorHooks.js +0 -17
  48. package/dist/createActorHooks.js.map +0 -1
  49. package/dist/createInfiniteQuery.d.ts +0 -185
  50. package/dist/createInfiniteQuery.d.ts.map +0 -1
  51. package/dist/createInfiniteQuery.js +0 -198
  52. package/dist/createInfiniteQuery.js.map +0 -1
  53. package/dist/createMutation.d.ts +0 -33
  54. package/dist/createMutation.d.ts.map +0 -1
  55. package/dist/createMutation.js +0 -199
  56. package/dist/createMutation.js.map +0 -1
  57. package/dist/createQuery.d.ts +0 -63
  58. package/dist/createQuery.d.ts.map +0 -1
  59. package/dist/createQuery.js +0 -204
  60. package/dist/createQuery.js.map +0 -1
  61. package/dist/createReactorProvider.d.ts +0 -158
  62. package/dist/createReactorProvider.d.ts.map +0 -1
  63. package/dist/createReactorProvider.js +0 -256
  64. package/dist/createReactorProvider.js.map +0 -1
  65. package/dist/createSuspenseInfiniteQuery.d.ts +0 -154
  66. package/dist/createSuspenseInfiniteQuery.d.ts.map +0 -1
  67. package/dist/createSuspenseInfiniteQuery.js +0 -209
  68. package/dist/createSuspenseInfiniteQuery.js.map +0 -1
  69. package/dist/createSuspenseQuery.d.ts +0 -46
  70. package/dist/createSuspenseQuery.d.ts.map +0 -1
  71. package/dist/createSuspenseQuery.js +0 -158
  72. package/dist/createSuspenseQuery.js.map +0 -1
  73. package/dist/defineDisplayReactor.d.ts +0 -43
  74. package/dist/defineDisplayReactor.d.ts.map +0 -1
  75. package/dist/defineDisplayReactor.js +0 -42
  76. package/dist/defineDisplayReactor.js.map +0 -1
  77. package/dist/defineReactor.d.ts +0 -99
  78. package/dist/defineReactor.d.ts.map +0 -1
  79. package/dist/defineReactor.js +0 -15
  80. package/dist/defineReactor.js.map +0 -1
  81. package/dist/defineReactorShared.d.ts +0 -84
  82. package/dist/defineReactorShared.d.ts.map +0 -1
  83. package/dist/defineReactorShared.js +0 -139
  84. package/dist/defineReactorShared.js.map +0 -1
  85. package/dist/hooks/createAuthHooks.d.ts +0 -50
  86. package/dist/hooks/createAuthHooks.d.ts.map +0 -1
  87. package/dist/hooks/createAuthHooks.js +0 -291
  88. package/dist/hooks/createAuthHooks.js.map +0 -1
  89. package/dist/hooks/index.d.ts +0 -21
  90. package/dist/hooks/index.d.ts.map +0 -1
  91. package/dist/hooks/index.js +0 -24
  92. package/dist/hooks/index.js.map +0 -1
  93. package/dist/hooks/useActorInfiniteQuery.d.ts +0 -67
  94. package/dist/hooks/useActorInfiniteQuery.d.ts.map +0 -1
  95. package/dist/hooks/useActorInfiniteQuery.js +0 -89
  96. package/dist/hooks/useActorInfiniteQuery.js.map +0 -1
  97. package/dist/hooks/useActorMethod.d.ts +0 -148
  98. package/dist/hooks/useActorMethod.d.ts.map +0 -1
  99. package/dist/hooks/useActorMethod.js +0 -394
  100. package/dist/hooks/useActorMethod.js.map +0 -1
  101. package/dist/hooks/useActorMutation.d.ts +0 -51
  102. package/dist/hooks/useActorMutation.d.ts.map +0 -1
  103. package/dist/hooks/useActorMutation.js +0 -70
  104. package/dist/hooks/useActorMutation.js.map +0 -1
  105. package/dist/hooks/useActorQuery.d.ts +0 -45
  106. package/dist/hooks/useActorQuery.d.ts.map +0 -1
  107. package/dist/hooks/useActorQuery.js +0 -67
  108. package/dist/hooks/useActorQuery.js.map +0 -1
  109. package/dist/hooks/useActorSuspenseInfiniteQuery.d.ts +0 -51
  110. package/dist/hooks/useActorSuspenseInfiniteQuery.d.ts.map +0 -1
  111. package/dist/hooks/useActorSuspenseInfiniteQuery.js +0 -76
  112. package/dist/hooks/useActorSuspenseInfiniteQuery.js.map +0 -1
  113. package/dist/hooks/useActorSuspenseQuery.d.ts +0 -32
  114. package/dist/hooks/useActorSuspenseQuery.d.ts.map +0 -1
  115. package/dist/hooks/useActorSuspenseQuery.js +0 -58
  116. package/dist/hooks/useActorSuspenseQuery.js.map +0 -1
  117. package/dist/ownedAuthentication.d.ts +0 -52
  118. package/dist/ownedAuthentication.d.ts.map +0 -1
  119. package/dist/ownedAuthentication.js +0 -49
  120. package/dist/ownedAuthentication.js.map +0 -1
  121. package/dist/server.d.ts +0 -21
  122. package/dist/server.d.ts.map +0 -1
  123. package/dist/server.js +0 -23
  124. package/dist/server.js.map +0 -1
  125. package/dist/testing.d.ts +0 -19
  126. package/dist/testing.d.ts.map +0 -1
  127. package/dist/testing.js +0 -19
  128. package/dist/testing.js.map +0 -1
  129. package/dist/types.d.ts +0 -671
  130. package/dist/types.d.ts.map +0 -1
  131. package/dist/types.js +0 -5
  132. package/dist/types.js.map +0 -1
  133. package/dist/utils.d.ts +0 -207
  134. package/dist/utils.d.ts.map +0 -1
  135. package/dist/utils.js +0 -405
  136. package/dist/utils.js.map +0 -1
  137. package/dist/validation.d.ts +0 -136
  138. package/dist/validation.d.ts.map +0 -1
  139. package/dist/validation.js +0 -144
  140. package/dist/validation.js.map +0 -1
  141. package/src/auth/auth-client-compat.ts +0 -273
  142. package/src/auth/authentication-manager.ts +0 -1682
  143. package/src/auth/constants.ts +0 -32
  144. package/src/auth/createIdentityAttributeHooks.ts +0 -169
  145. package/src/auth/identity-attributes-manager.ts +0 -226
  146. package/src/auth/identity-attributes.ts +0 -345
  147. package/src/auth/index.ts +0 -7
  148. package/src/auth/local-ii-probe.ts +0 -173
  149. package/src/auth/types.ts +0 -243
  150. package/src/createActorHooks.ts +0 -208
  151. package/src/createInfiniteQuery.ts +0 -670
  152. package/src/createMutation.ts +0 -324
  153. package/src/createQuery.ts +0 -369
  154. package/src/createReactorProvider.ts +0 -365
  155. package/src/createSuspenseInfiniteQuery.ts +0 -651
  156. package/src/createSuspenseQuery.ts +0 -304
  157. package/src/defineDisplayReactor.ts +0 -62
  158. package/src/defineReactor.ts +0 -142
  159. package/src/defineReactorShared.ts +0 -268
  160. package/src/hooks/createAuthHooks.ts +0 -371
  161. package/src/hooks/index.ts +0 -103
  162. package/src/hooks/useActorInfiniteQuery.ts +0 -278
  163. package/src/hooks/useActorMethod.ts +0 -710
  164. package/src/hooks/useActorMutation.ts +0 -205
  165. package/src/hooks/useActorQuery.ts +0 -157
  166. package/src/hooks/useActorSuspenseInfiniteQuery.ts +0 -248
  167. package/src/hooks/useActorSuspenseQuery.ts +0 -147
  168. package/src/index.ts +0 -31
  169. package/src/ownedAuthentication.ts +0 -81
  170. package/src/server.ts +0 -23
  171. package/src/testing.ts +0 -18
  172. package/src/types.ts +0 -948
  173. package/src/utils.ts +0 -505
  174. package/src/validation.ts +0 -226
@@ -1,710 +0,0 @@
1
- import {
2
- useCallback,
3
- useEffect,
4
- useInsertionEffect,
5
- useMemo,
6
- useRef,
7
- } from "react"
8
- import {
9
- useQuery,
10
- useMutation,
11
- hashKey,
12
- type UseQueryResult,
13
- type UseMutationResult,
14
- type QueryKey,
15
- type QueryObserverOptions,
16
- } from "@tanstack/react-query"
17
- import {
18
- Reactor,
19
- BaseActor,
20
- FunctionName,
21
- TransformKey,
22
- ReactorArgs,
23
- ReactorReturnOk,
24
- ReactorQueryData,
25
- ReactorReturnErr,
26
- FunctionType,
27
- } from "@ic-reactor/core"
28
- import { CallConfig } from "@icp-sdk/core/agent"
29
- import {
30
- invalidateTargets,
31
- normalizeQueryData,
32
- pickFetchOptions,
33
- useMountQueryClient,
34
- } from "../utils.js"
35
- import type { InvalidationTarget } from "../types.js"
36
-
37
- /**
38
- * Configuration for useActorMethod hook.
39
- * Extends react-query's QueryObserverOptions with custom reactor params.
40
- *
41
- * This is a unified hook that handles both query and mutation methods.
42
- * Query-specific options (like refetchInterval) only apply to query methods.
43
- * Mutation-specific options (like invalidateQueries) only apply to mutation methods.
44
- *
45
- * `retry`, `retryDelay`, `networkMode` and `meta` decide how a call runs, so
46
- * they apply to both. An update method's call is a mutation: without a `retry`
47
- * here it follows the QueryClient's mutation defaults, which retry nothing
48
- * unless the app set `mutations.retry`, because each attempt runs the update
49
- * on the canister again. Its query defaults, such as `reactorRetry`, do not
50
- * apply to it.
51
- */
52
- export interface UseActorMethodParameters<
53
- Service = BaseActor,
54
- Method extends FunctionName<Service> = FunctionName<Service>,
55
- Transform extends TransformKey = "candid",
56
- > extends Omit<
57
- QueryObserverOptions<
58
- ReactorQueryData<ReactorReturnOk<Service, Method, Transform>>,
59
- ReactorReturnErr<Service, Method, Transform>,
60
- ReactorQueryData<ReactorReturnOk<Service, Method, Transform>>,
61
- ReactorQueryData<ReactorReturnOk<Service, Method, Transform>>,
62
- QueryKey
63
- >,
64
- "queryKey" | "queryFn"
65
- > {
66
- /** The reactor instance to use for method calls */
67
- reactor: Reactor<Service, Transform>
68
-
69
- /** The method name to call on the canister */
70
- functionName: Method
71
-
72
- /** Arguments to pass to the method (optional for parameterless methods) */
73
- args?: ReactorArgs<Service, Method, Transform>
74
-
75
- /** Agent call configuration (effectiveCanisterId, etc.) */
76
- callConfig?: CallConfig
77
-
78
- /** Custom query key (auto-generated if not provided) */
79
- queryKey?: QueryKey
80
-
81
- /**
82
- * Callback when the method call succeeds.
83
- * Works for both query and mutation methods.
84
- *
85
- * A method's `undefined` result arrives as `null`, as in `useActorQuery`,
86
- * for query and update methods alike.
87
- */
88
- onSuccess?: (
89
- data: ReactorQueryData<ReactorReturnOk<Service, Method, Transform>>
90
- ) => void
91
-
92
- /**
93
- * Callback when the method call fails.
94
- * Works for both query and mutation methods.
95
- */
96
- onError?: (error: ReactorReturnErr<Service, Method, Transform>) => void
97
-
98
- /**
99
- * Queries to invalidate after a successful mutation.
100
- * Only applies to mutation methods (updates).
101
- *
102
- * Each entry is a query key, a query object or query factory, or a
103
- * `{ functionName, args? }` method of `reactor`; see
104
- * {@link InvalidationTarget}. `undefined` entries are skipped.
105
- *
106
- * The invalidation is awaited before `onSuccess` runs, as in
107
- * `useActorMutation` and `createMutation`, so `onSuccess` sees the
108
- * refetched data, and `call()` resolves once the invalidated queries in use
109
- * have refetched.
110
- */
111
- invalidateQueries?: InvalidationTarget<Service, Transform>[]
112
- }
113
-
114
- /**
115
- * Configuration type for bound useActorMethod hook (reactor omitted).
116
- * For use with createActorHooks.
117
- */
118
- export type UseActorMethodConfig<
119
- Service = BaseActor,
120
- Method extends FunctionName<Service> = FunctionName<Service>,
121
- Transform extends TransformKey = "candid",
122
- > = Omit<UseActorMethodParameters<Service, Method, Transform>, "reactor">
123
-
124
- /**
125
- * Result type for useActorMethod hook.
126
- * Provides a unified interface for both query and mutation methods.
127
- */
128
- export interface UseActorMethodResult<
129
- Service = BaseActor,
130
- Method extends FunctionName<Service> = FunctionName<Service>,
131
- Transform extends TransformKey = "candid",
132
- > {
133
- /**
134
- * The returned data from the method call. A method's `undefined` result is
135
- * `null` here, as in `useActorQuery`, so `undefined` means that no call has
136
- * settled yet, that the last call failed, or that an update call is
137
- * running. A query keeps its earlier data when a refetch fails.
138
- */
139
- data:
140
- ReactorQueryData<ReactorReturnOk<Service, Method, Transform>> | undefined
141
-
142
- /** Whether the method is currently executing */
143
- isLoading: boolean
144
-
145
- /** Alias for isLoading - whether a mutation is pending */
146
- isPending: boolean
147
-
148
- /** Whether there was an error */
149
- isError: boolean
150
-
151
- /** Whether the method has successfully completed at least once */
152
- isSuccess: boolean
153
-
154
- /** The error if one occurred */
155
- error: ReactorReturnErr<Service, Method, Transform> | null
156
-
157
- /** Whether this is a query method (true) or mutation method (false) */
158
- isQuery: boolean
159
-
160
- /** The function type (query, update, composite_query) */
161
- functionType: FunctionType
162
-
163
- /**
164
- * Call the method with optional arguments.
165
- * For queries: triggers a refetch
166
- * For mutations: executes the mutation with the provided args
167
- *
168
- * For a query method, `call(args)` fetches those args from the canister
169
- * even when they are cached, and reports the result to `onSuccess` or
170
- * `onError` itself. `call()` refetches the hook's own args, as `refetch()`
171
- * does. Either resolves `undefined` when its fetch fails. A sign-in or
172
- * sign-out while either is in flight cancels the fetch, which then runs
173
- * again for the principal signed in, so the call resolves with that
174
- * principal's answer rather than the previous one's; see
175
- * `ClientManager.fetchAcrossIdentitySwitch`.
176
- */
177
- call: (
178
- args?: ReactorArgs<Service, Method, Transform>
179
- ) => Promise<
180
- ReactorQueryData<ReactorReturnOk<Service, Method, Transform>> | undefined
181
- >
182
-
183
- /**
184
- * Reset the state (data and error).
185
- * For queries: resets this hook's own cache entry to its initial state, so
186
- * `data` goes back to `initialData` when one was given and is cleared
187
- * otherwise. An enabled hook then refetches. Other args of the same method
188
- * are left alone.
189
- * For mutations: resets the mutation state
190
- */
191
- reset: () => void
192
-
193
- /**
194
- * For queries only: Refetch the query
195
- *
196
- * Resolves with the answer, or `undefined` when the refetch fails, whose
197
- * error the hook reports to `onError`; `data` keeps the last answer. A
198
- * sign-in or sign-out while it is in flight makes it refetch for the
199
- * principal signed in, and it resolves with that principal's answer, as
200
- * `call()` does.
201
- */
202
- refetch: () => Promise<
203
- ReactorQueryData<ReactorReturnOk<Service, Method, Transform>> | undefined
204
- >
205
-
206
- // Expose underlying results for advanced use cases
207
- /** The raw query result (only available for query methods) */
208
- queryResult?: UseQueryResult<
209
- ReactorQueryData<ReactorReturnOk<Service, Method, Transform>>,
210
- ReactorReturnErr<Service, Method, Transform>
211
- >
212
-
213
- /** The raw mutation result (only available for mutation methods) */
214
- mutationResult?: UseMutationResult<
215
- ReactorQueryData<ReactorReturnOk<Service, Method, Transform>>,
216
- ReactorReturnErr<Service, Method, Transform>,
217
- ReactorArgs<Service, Method, Transform>
218
- >
219
- }
220
-
221
- /**
222
- * A ref to `value` as of the last committed render, for code that runs outside
223
- * render: event handlers, timers, effects and TanStack callbacks.
224
- *
225
- * Assigning the ref during render would also publish renders that React throws
226
- * away, such as a transition that suspends or one that a more urgent update
227
- * interrupts. The tree still on screen would then act on props it never showed,
228
- * like calling a method it does not render. An insertion effect runs only when
229
- * its render commits, and before every layout and passive effect of that
230
- * commit, so no effect anywhere in the tree reads the previous commit's value.
231
- * React's own `useEffectEvent` also swaps in its new function during the
232
- * commit, ahead of layout effects. Unlike `useLayoutEffect`, an insertion
233
- * effect does not warn in a React 18 server render. The initial value serves
234
- * anything that runs before the first commit.
235
- */
236
- function useCommittedRef<T>(value: T): { readonly current: T } {
237
- const ref = useRef(value)
238
- useInsertionEffect(() => {
239
- ref.current = value
240
- })
241
- return ref
242
- }
243
-
244
- /**
245
- * A unified hook for calling canister methods that automatically handles
246
- * both query and mutation methods based on the Candid interface.
247
- */
248
- export function useActorMethod<
249
- Service = BaseActor,
250
- Method extends FunctionName<Service> = FunctionName<Service>,
251
- Transform extends TransformKey = "candid",
252
- >({
253
- reactor,
254
- functionName,
255
- args,
256
- callConfig,
257
- queryKey: customQueryKey,
258
- enabled = true,
259
- onSuccess,
260
- onError,
261
- invalidateQueries,
262
- ...queryOptions
263
- }: UseActorMethodParameters<Service, Method, Transform>): UseActorMethodResult<
264
- Service,
265
- Method,
266
- Transform
267
- > {
268
- type TData = ReactorReturnOk<Service, Method, Transform>
269
- type TQueryData = ReactorQueryData<TData>
270
-
271
- // Determine if this is a query method by checking the IDL
272
- const isQuery = useMemo(() => {
273
- if (!reactor) throw new Error("Reactor instance is required")
274
- return reactor.isQueryMethod(functionName)
275
- }, [reactor, functionName])
276
-
277
- const functionType: FunctionType = isQuery ? "query" : "update"
278
-
279
- useMountQueryClient(reactor.queryClient)
280
-
281
- // The committed render's callbacks, read at dispatch time: this keeps a
282
- // rerendered closure from being ignored, and keeps callback identity out of
283
- // the effect deps.
284
- const onSuccessRef = useCommittedRef(onSuccess)
285
- const onErrorRef = useCommittedRef(onError)
286
-
287
- // Build the key for a given set of call arguments.
288
- //
289
- // A custom `queryKey` is appended to the canister/function prefix rather than
290
- // replacing it, matching `useActorQuery`. Used verbatim it would carry no
291
- // canister id, so the entry would be invisible to the canister-scoped
292
- // invalidation `ClientManager.updateAgent` runs on identity change and would
293
- // keep serving the previous principal's data after sign-in or sign-out.
294
- const buildQueryKey = useCallback(
295
- (keyArgs: ReactorArgs<Service, Method, Transform> | undefined): QueryKey =>
296
- reactor.generateQueryKey(
297
- { functionName, args: keyArgs, queryKey: customQueryKey },
298
- callConfig
299
- ),
300
- // `canisterId` is mutable reactor state that `setCanisterId` can change,
301
- // while `reactor` itself stays the same object — so it has to be a
302
- // dependency in its own right or the key stays pinned to the old canister.
303
- [
304
- reactor,
305
- reactor.canisterId?.toString(),
306
- functionName,
307
- callConfig,
308
- customQueryKey,
309
- ]
310
- )
311
-
312
- const queryKey = useMemo(() => buildQueryKey(args), [buildQueryKey, args])
313
-
314
- // ============================================================================
315
- // Query Implementation
316
- // ============================================================================
317
-
318
- const queryResult = useQuery<
319
- TQueryData,
320
- ReactorReturnErr<Service, Method, Transform>
321
- >(
322
- {
323
- queryKey,
324
- // Callbacks deliberately do NOT live here: a queryFn runs once per fetch
325
- // attempt, so `onError` fired on every retry (four times with the default
326
- // QueryClient) and `onSuccess` never fired when data came from the cache
327
- // or a deduped sibling. They are dispatched from the settled observer
328
- // result below instead.
329
- //
330
- // TanStack Query fails a query whose queryFn resolves `undefined`, with
331
- // "data is undefined", and a successful call can resolve it. A
332
- // DisplayReactor decodes an `opt` None to `undefined`, and a `()` query
333
- // returns nothing. Every other query path normalizes the value to `null`.
334
- queryFn: async () =>
335
- normalizeQueryData<TData>(
336
- (await reactor.callMethod({
337
- functionName,
338
- args,
339
- callConfig,
340
- })) as TData
341
- ),
342
- enabled: isQuery && enabled,
343
- ...queryOptions,
344
- },
345
- reactor.queryClient
346
- )
347
-
348
- // Dispatch the query callbacks from the settled observer result, once per
349
- // distinct outcome. TanStack v5 removed `onSuccess`/`onError` from useQuery
350
- // for exactly this reason, so the settle timestamps are what identify a new
351
- // result: they also advance for a cache hit on a fresh mount, which is the
352
- // case that previously never notified at all.
353
- const notifiedSuccessAt = useRef<number | undefined>(undefined)
354
- const notifiedErrorAt = useRef<number | undefined>(undefined)
355
-
356
- const {
357
- status,
358
- data,
359
- error,
360
- dataUpdatedAt,
361
- errorUpdatedAt,
362
- isPlaceholderData,
363
- isFetched,
364
- } = queryResult
365
-
366
- useEffect(() => {
367
- if (!isQuery) return
368
- // Placeholder data also has `status: "success"`, but no call has returned
369
- // it: it is the `placeholderData` option, or with `keepPreviousData` the
370
- // previous args' result standing in while this call is in flight.
371
- if (isPlaceholderData) return
372
- // So does `initialData`: an entry starts with it, and `reset()` puts it
373
- // back, before any fetch of the entry has settled. The first fetch that
374
- // settles makes the entry fetched, and its result is reported below.
375
- if (!isFetched) return
376
- if (status === "success" && dataUpdatedAt !== notifiedSuccessAt.current) {
377
- notifiedSuccessAt.current = dataUpdatedAt
378
- onSuccessRef.current?.(data)
379
- }
380
- }, [isQuery, status, data, dataUpdatedAt, isPlaceholderData, isFetched])
381
-
382
- useEffect(() => {
383
- if (!isQuery) return
384
- if (status === "error" && errorUpdatedAt !== notifiedErrorAt.current) {
385
- notifiedErrorAt.current = errorUpdatedAt
386
- onErrorRef.current?.(
387
- error as ReactorReturnErr<Service, Method, Transform>
388
- )
389
- }
390
- }, [isQuery, status, error, errorUpdatedAt])
391
-
392
- // `call(args)` reports its own outcome, once per call, because the args it
393
- // fetched usually key an entry this observer does not watch. When they key
394
- // the entry it does watch, the effects above see the same settle, and each
395
- // callback used to fire twice for one call. So the settle that ends a call's
396
- // fetch is marked as notified when it lands in the observed entry, and the
397
- // effects skip it.
398
- //
399
- // A query cache listener sets that mark while TanStack dispatches the
400
- // settle, before any render can show it. Matching a settle up by its
401
- // timestamp afterwards could not tell settles apart: two in one millisecond
402
- // share a timestamp. And a call that an identity switch cancels settles
403
- // nothing: TanStack reverts the entry to its previous result, timestamp
404
- // included, so the call's outcome looked reported already, and neither the
405
- // call nor the effects reported it.
406
- const observedKeyRef = useCommittedRef(queryKey)
407
- const markCallSettle = (calledKey: QueryKey): (() => void) => {
408
- const { queryClient } = reactor
409
- // The hash TanStack files the called entry under, worked out the way
410
- // `fetchQuery` does. The listener compares it with hashes TanStack has
411
- // already computed rather than hashing keys itself: the QueryClient may be
412
- // shared with the app, whose keys a custom `queryKeyHashFn` can let hold
413
- // values that `hashKey` throws on, inside TanStack's dispatch.
414
- const calledHash = queryClient.defaultQueryOptions({
415
- queryKey: calledKey,
416
- }).queryHash
417
- let settled = false
418
- return queryClient.getQueryCache().subscribe((event) => {
419
- if (settled || event.type !== "updated") return
420
- const { action, query } = event
421
- // A fetch settles with one of these. `setQueryData` dispatches a
422
- // success too, flagged manual, and it does not end this call's fetch.
423
- const isSettle =
424
- action.type === "error" || (action.type === "success" && !action.manual)
425
- if (!isSettle || query.queryHash !== calledHash) return
426
- settled = true
427
- if (hashKey(calledKey) !== hashKey(observedKeyRef.current)) return
428
- if (action.type === "success") {
429
- notifiedSuccessAt.current = query.state.dataUpdatedAt
430
- } else {
431
- notifiedErrorAt.current = query.state.errorUpdatedAt
432
- }
433
- })
434
- }
435
-
436
- // ============================================================================
437
- // Mutation Implementation
438
- // ============================================================================
439
-
440
- const mutationResult = useMutation<
441
- TQueryData,
442
- ReactorReturnErr<Service, Method, Transform>,
443
- ReactorArgs<Service, Method, Transform>
444
- >(
445
- {
446
- mutationKey: queryKey,
447
- // The hook's `retry`, `retryDelay`, `networkMode` and `meta`, the options
448
- // that decide how a call runs, as the query branch's `call()` applies
449
- // them. They reached only the query branch, so an update's call ignored
450
- // them: it stayed paused offline under `networkMode: "always"` and
451
- // reached the MutationCache callbacks without the hook's `meta`. Unset
452
- // ones are left to the QueryClient's mutation defaults, which retry
453
- // nothing unless the app set `mutations.retry`: each attempt of an
454
- // update is a new call the canister runs, so only a `retry` given here
455
- // or in those defaults sends one again.
456
- ...pickFetchOptions(queryOptions),
457
- // Normalized like the query branch, so `data`, `call()` and `onSuccess`
458
- // mean the same thing for both kinds of method. The hook cannot type the
459
- // two branches apart: a Candid service type does not say which methods
460
- // are queries.
461
- mutationFn: async (mutationArgs) =>
462
- normalizeQueryData<TData>(
463
- (await reactor.callMethod({
464
- functionName,
465
- args: mutationArgs ?? args,
466
- callConfig,
467
- })) as TData
468
- ),
469
- // Invalidation first, then `onSuccess`, as `useActorMutation` and
470
- // `createMutation` do. TanStack Query waits for the promise returned
471
- // here before it settles the mutation, so `call()` resolves, and
472
- // `isPending` turns false, once the invalidated queries that are in use
473
- // have refetched, and `onSuccess` reads the refetched data. A refetch
474
- // that fails does not reject `invalidateQueries`, so it cannot turn the
475
- // update, which has already run on the canister, into a failure.
476
- onSuccess: async (data) => {
477
- await invalidateTargets(reactor, invalidateQueries, callConfig)
478
- onSuccessRef.current?.(data)
479
- },
480
- onError: (error) => {
481
- onErrorRef.current?.(error)
482
- },
483
- },
484
- reactor.queryClient
485
- )
486
-
487
- // ============================================================================
488
- // Refetch and Call Functions
489
- // ============================================================================
490
-
491
- // A query's `call()` and `refetch()` resolve with the answer for the
492
- // principal signed in when they settle. `ClientManager.updateAgent` cancels
493
- // a fetch in flight when a sign-in or sign-out switches the principal, so
494
- // that the previous principal's answer is never cached. TanStack then
495
- // resolves the fetch with the data it puts the entry back to, which is the
496
- // previous principal's, or rejects it with a `CancelledError` when the entry
497
- // had none, and a call used to resolve with, and report, whichever it got.
498
- // Through `fetchAcrossIdentitySwitch` it runs again for the principal signed
499
- // in, as `reactor.fetchQuery()` and the factories' `fetch()` do. When the
500
- // principal switches during that run too, and during each of two more, that
501
- // rejects with a `CallError`, which is reported to `onError` like any other
502
- // failure.
503
-
504
- const refetchLatest = async (): Promise<TQueryData | undefined> => {
505
- if (!isQuery) return undefined
506
- let runs = 0
507
- try {
508
- const result = await reactor.clientManager.fetchAcrossIdentitySwitch(() =>
509
- // A run after a switch joins the refetch the switch started for
510
- // this entry, rather than cancel it and start another.
511
- queryResult.refetch(runs++ === 0 ? undefined : { cancelRefetch: false })
512
- )
513
- // TanStack's `refetch()` resolves even when the fetch fails, with the
514
- // entry's last answer still in the result. After a sign-in or sign-out
515
- // that is the previous principal's: the entry is put back to it when
516
- // the switch cancels a fetch, and keeps it when the new principal's
517
- // refetch fails. So a failed refetch resolves `undefined`, as a failed
518
- // `call(args)` does, and the effects report the failure to `onError`.
519
- // The hook's `data` keeps the last answer, as TanStack's does.
520
- return result.isError ? undefined : result.data
521
- } catch (error) {
522
- // Only that CallError: `refetch()` itself never rejects. The effects
523
- // report what the entry settles with, and it settles nothing for this.
524
- onErrorRef.current?.(
525
- error as ReactorReturnErr<Service, Method, Transform>
526
- )
527
- return undefined
528
- }
529
- }
530
-
531
- const callLatest = async (
532
- callArgs?: ReactorArgs<Service, Method, Transform>
533
- ): Promise<TQueryData | undefined> => {
534
- if (isQuery) {
535
- // For queries, refetch with new args if provided
536
- if (callArgs !== undefined) {
537
- // Key on the args actually being called. Reusing the hook's
538
- // mount-time key would store this result under the previous args'
539
- // entry — poisoning it for every other reader — and let fetchQuery
540
- // dedupe onto an in-flight request for the old args, returning that
541
- // response as though it answered this one.
542
- const calledKey = buildQueryKey(callArgs)
543
- // Reported here rather than by the observer effects: this result
544
- // usually lands under a key the mounted observer (bound to the hook's
545
- // own args) does not watch. When it is that key, `markCallSettle` has
546
- // already kept the effects from reporting it as well. Either way the
547
- // callbacks get what the call settles with.
548
- try {
549
- const result = await reactor.clientManager.fetchAcrossIdentitySwitch(
550
- async () => {
551
- // Each run marks the settle of its own fetch. A run a switch
552
- // overtook may have settled with the previous principal's answer,
553
- // which the effects must not report either.
554
- const stopMarking = markCallSettle(calledKey)
555
- try {
556
- return await reactor.queryClient.fetchQuery<
557
- TQueryData,
558
- ReactorReturnErr<Service, Method, Transform>
559
- >({
560
- // The options the hook's own fetches run with: `retry`,
561
- // `retryDelay`, `networkMode` and `meta`. With only a key and
562
- // a function, a call ran on the QueryClient's defaults. It
563
- // failed on the first error the hook retried through, stayed
564
- // paused offline under `networkMode: "always"`, and reached
565
- // the QueryCache callbacks without the hook's `meta`.
566
- ...pickFetchOptions(queryOptions),
567
- queryKey: calledKey,
568
- // Normalize for the same reason as the observer's queryFn.
569
- queryFn: async () =>
570
- normalizeQueryData<TData>(
571
- (await reactor.callMethod({
572
- functionName,
573
- args: callArgs,
574
- callConfig,
575
- })) as TData
576
- ),
577
- staleTime: 0,
578
- })
579
- } finally {
580
- stopMarking()
581
- }
582
- }
583
- )
584
- onSuccessRef.current?.(result)
585
- return result
586
- } catch (error) {
587
- onErrorRef.current?.(
588
- error as ReactorReturnErr<Service, Method, Transform>
589
- )
590
- return undefined
591
- }
592
- }
593
- // Otherwise just refetch
594
- return refetchLatest()
595
- } else {
596
- // For mutations, execute with provided args
597
- return mutationResult
598
- .mutateAsync(callArgs as ReactorArgs<Service, Method, Transform>)
599
- .catch(() => undefined)
600
- }
601
- }
602
-
603
- // ============================================================================
604
- // Reset Function
605
- // ============================================================================
606
-
607
- const resetLatest = () => {
608
- if (isQuery) {
609
- // Reset, not remove. `removeQueries` drops the entry without notifying
610
- // its observers, so this hook kept rendering the old data while bound to
611
- // a query that was no longer in the cache. No later invalidation reached
612
- // it, including the one an identity switch runs. `resetQueries` notifies
613
- // the observer and refetches the entry when the hook is enabled. It is
614
- // `exact` because only this hook's entry should reset. A prefix match on
615
- // a no-args key would also reset every args variant other hooks render.
616
- void reactor.queryClient.resetQueries({ queryKey, exact: true })
617
- } else {
618
- mutationResult.reset()
619
- }
620
- }
621
-
622
- // `call`, `reset` and `refetch` keep one identity for the life of the
623
- // component, as TanStack's own `refetch`, `mutate` and `reset` do, and run
624
- // the latest committed render's implementation above when invoked. They used
625
- // to be `useCallback`s listing the query and mutation results, which TanStack
626
- // Query returns fresh every render, so they changed every render too. An
627
- // effect that lists one — `react-hooks/exhaustive-deps` requires it as soon
628
- // as the effect calls it — then re-ran after every render its own call
629
- // caused: an unbounded loop of canister calls, state-changing ones for an
630
- // update method.
631
- const latest = useCommittedRef({
632
- call: callLatest,
633
- reset: resetLatest,
634
- refetch: refetchLatest,
635
- })
636
-
637
- const call = useCallback(
638
- (callArgs?: ReactorArgs<Service, Method, Transform>) =>
639
- latest.current.call(callArgs),
640
- []
641
- )
642
- const reset = useCallback(() => latest.current.reset(), [])
643
- const refetch = useCallback(() => latest.current.refetch(), [])
644
-
645
- // ============================================================================
646
- // Return Unified Result
647
- // ============================================================================
648
-
649
- if (isQuery) {
650
- return {
651
- data: queryResult.data,
652
- isLoading: queryResult.isLoading,
653
- isPending: queryResult.isLoading,
654
- isError: queryResult.isError,
655
- isSuccess: queryResult.isSuccess,
656
- error: queryResult.error,
657
- isQuery: true,
658
- functionType,
659
- call,
660
- reset,
661
- refetch,
662
- queryResult,
663
- } as UseActorMethodResult<Service, Method, Transform>
664
- } else {
665
- return {
666
- data: mutationResult.data,
667
- isLoading: mutationResult.isPending,
668
- isPending: mutationResult.isPending,
669
- isError: mutationResult.isError,
670
- isSuccess: mutationResult.isSuccess,
671
- error: mutationResult.error,
672
- isQuery: false,
673
- functionType,
674
- call,
675
- reset,
676
- refetch,
677
- mutationResult,
678
- } as UseActorMethodResult<Service, Method, Transform>
679
- }
680
- }
681
-
682
- /**
683
- * Creates a bound useMethod hook for a specific reactor instance.
684
- *
685
- * @example
686
- * ```tsx
687
- * const { useMethod } = createActorMethodHooks(reactor)
688
- * ```
689
- */
690
- export function createActorMethodHooks<
691
- Service = BaseActor,
692
- Transform extends TransformKey = "candid",
693
- >(reactor: Reactor<Service, Transform>) {
694
- return {
695
- /**
696
- * Hook for calling methods on the bound reactor.
697
- */
698
- useMethod: <Method extends FunctionName<Service>>(
699
- config: Omit<
700
- UseActorMethodParameters<Service, Method, Transform>,
701
- "reactor"
702
- >
703
- ) =>
704
- useActorMethod({ ...config, reactor } as UseActorMethodParameters<
705
- Service,
706
- Method,
707
- Transform
708
- >),
709
- }
710
- }