| author | |
| committer | |
| log | de7e1ab0f88b02444249d69a59c5fed7c981b6c9 |
| tree | df9542e7a2599e14d6b9ade21edb5d9f27b34088 |
| parent | b222f6adf6944284280e7ff42bdb6bb2242bce84 |
| signature |
9 files changed, 289 insertions(+), 170 deletions(-)
example/src/App.tsx+3-3| ... | ... | @@ -3,7 +3,7 @@ import { |
| 3 | 3 | createMutationButton, |
| 4 | 4 | MutationClient, |
| 5 | 5 | queryClientOptimisticHelpers, |
| 6 | useMutation, | |
| 6 | useMutate, | |
| 7 | 7 | } from "@clo/react-mutation"; |
| 8 | 8 | import { queryOptions as queryOptions } from "@tanstack/react-query"; |
| 9 | 9 | import { useSuspenseQuery } from "@tanstack/react-query"; |
| ... | ... | @@ -49,7 +49,7 @@ const queryCounter = queryOptions({ |
| 49 | 49 | // await client.invalidateQueries(queryCounter); |
| 50 | 50 | // }, |
| 51 | 51 | // }); |
| 52 | const mutIncrement = mutationClient.defineBatched({ | |
| 52 | const mutIncrement = mutationClient.defineDebounced({ | |
| 53 | 53 | mode: "debounce", |
| 54 | 54 | time: 200, |
| 55 | 55 | |
| ... | ... | @@ -92,7 +92,7 @@ const MutationButton = createMutationButton(CustomButton); |
| 92 | 92 | |
| 93 | 93 | function Counter() { |
| 94 | 94 | const { data: { count } } = useSuspenseQuery(queryCounter); |
| 95 | const mutation = useMutation(mutIncrement); | |
| 95 | const mutation = useMutate(mutIncrement); | |
| 96 | 96 | |
| 97 | 97 | return ( |
| 98 | 98 | <div className="counter-card"> |
readme.md+74-28| ... | ... | @@ -10,7 +10,7 @@ patterns and verbose code that is hard to review. |
| 10 | 10 | |
| 11 | 11 | The primary gains React Mutation provides are |
| 12 | 12 | |
| 13 | - **Automatic error handling**. If a `useMutation` hook does not observe | |
| 13 | - **Automatic error handling**. If a `useMutate` hook does not observe | |
| 14 | 14 | `isError`, unhandled errors will be propagated to a global handler, which can |
| 15 | 15 | display a UI toast. Otherwise, the component can display the error locally. |
| 16 | 16 | - Optimistic helpers allow defining rollbacks and refetching logic independant |
| ... | ... | @@ -22,13 +22,13 @@ The primary gains React Mutation provides are |
| 22 | 22 | This library declares two kinds of mutations. Each kind has different behavior |
| 23 | 23 | around concurrent operations. |
| 24 | 24 | |
| 25 | - [**Queued Mutations**](#Queued-Mutations): A mutation blocks the UI until it | |
| 25 | - [**Blocking Mutations**](#Blocking-Mutations): A mutation blocks the UI until it | |
| 26 | 26 | is complete. You press a button, a pending state appears, then it completes. |
| 27 | 27 | This works great for forms, creations and deletions, and is similar to React |
| 28 | 28 | Query's mutation system. |
| 29 | - [**Batched Mutations**](#Batched-Mutations): Each call to the mutation applies | |
| 30 | new optimistic state, and after a debounce or throttle, the new optimistic | |
| 31 | state is committed to the API. UI never shows a pending state for batches. | |
| 29 | - [**Debounced Mutations**](#Debounced-Mutations): Each call to the mutation applies | |
| 30 | new optimistic state, and after a debounce (or throttle) the new optimistic | |
| 31 | state is committed to the API. UI never shows a pending state for these. | |
| 32 | 32 | This works great for auto-saving input fields, follow buttons, and is |
| 33 | 33 | preferred whenever possible. |
| 34 | 34 | |
| ... | ... | @@ -37,7 +37,7 @@ React Mutation starts with a `MutationClient`, which shares global state for an |
| 37 | 37 | ```ts |
| 38 | 38 | const queryClient = new QueryClient(); |
| 39 | 39 | export const mutations = new MutationClient({ |
| 40 | // All properties in `context` are available within mutation functions. | |
| 40 | // All properties in `context` are available within every function. | |
| 41 | 41 | context: { |
| 42 | 42 | client: queryClient, |
| 43 | 43 | // Can add any easy helpers for your codebase. |
| ... | ... | @@ -45,29 +45,40 @@ export const mutations = new MutationClient({ |
| 45 | 45 | get: (k: QueryKey) => client.getQueryData(k), |
| 46 | 46 | }, |
| 47 | 47 | |
| 48 | // Optimistic helpers are a second type of context, only available | |
| 49 | // within optimistic update functions. The built in React Query helpers | |
| 50 | // add many query cache mutating operations that automatically | |
| 48 | // Optimistic helpers are a second type of context, only available within | |
| 49 | // optimistic update functions. These functions are bound to each mutation, | |
| 50 | // which means they can handle automatic rollbacks and query invalidation. | |
| 51 | 51 | getOptimisticHelpers: queryClientOptimisticHelpers(queryClient), |
| 52 | 52 | |
| 53 | 53 | // When call sites do not opt into handling errors, or a pending |
| 54 | 54 | // mutation hook is unmounted, errors are sent to this function. |
| 55 | 55 | // An example is to bind this to global a UI toast. |
| 56 | reportError(description: string, error: unknown) { | |
| 57 | console.error("Mutation error:", error); | |
| 56 | reportError(userFriendlyErrorMessage: string, error: unknown) { | |
| 57 | showToastUI("error", userFriendlyErrorMessage); | |
| 58 | console.error(error); // or send to telemetry | |
| 59 | }, | |
| 60 | ||
| 61 | // Similarly, when call sites do opt into handling success. | |
| 62 | reportSuccess(userFriendlySuccessMessage: string) { | |
| 63 | showToastUI("success", userFriendlyErrorMessage); | |
| 58 | 64 | }, |
| 59 | 65 | }) |
| 60 | 66 | |
| 61 | 67 | ``` |
| 62 | 68 | |
| 63 | ### Queued Mutations | |
| 69 | ### Blocking Mutations | |
| 64 | 70 | |
| 65 | A queued mutation is defined with `mutations.defineQueued`. | |
| 71 | A blocking mutation is defined with `mutations.defineBlocking`. Example use cases: | |
| 72 | ||
| 73 | - A form to create a new resource. | |
| 74 | - Button operations such as deleting or resyncing. | |
| 75 | - Any case where it is unclear what the optimistic state should be. | |
| 66 | 76 | |
| 67 | 77 | ```tsx |
| 68 | 78 | const queryItemList = queryOptions({ ... }); |
| 69 | 79 | const queryItem = (id: string) => queryOptions({ ... }); |
| 70 | 80 | |
| 81 | // The convention is to name handlers starting with `mut` | |
| 71 | 82 | const mutDeleteItem = mutations.defineQueued({ |
| 72 | 83 | // `mutate` comes first, is only worried about syncing with the backend. |
| 73 | 84 | async mutate(id: string) { |
| ... | ... | @@ -76,23 +87,31 @@ const mutDeleteItem = mutations.defineQueued({ |
| 76 | 87 | }, |
| 77 | 88 | |
| 78 | 89 | optimistic({ client, get, helpers, args: [id] }) { |
| 90 | // Remove the matching items, but restore and refetch them on failure. | |
| 79 | 91 | helpers.arrayRemove(queryItemList, (item) => item === id); |
| 92 | // Remove this query from the client, but restore as stale and refetch it on failure. | |
| 80 | 93 | helpers.removeQuery(queryItem); |
| 81 | 94 | }, |
| 82 | 95 | |
| 96 | // Example: `Could not {description}` | |
| 83 | 97 | describe({ get, args: [id] }) { |
| 84 | 98 | const title = get(queryItem().queryKey)?.title ?? "Unknown Item"; |
| 85 | return `delete '${title}'`; | |
| 99 | return `Delete '${get(queryItem(id))?.title ?? 'unknown'}'`; | |
| 86 | 100 | }, |
| 101 | // Example: `Successfully {description}` | |
| 102 | describeResult: ({ get, args: [id] }) => | |
| 103 | `Deleted '${get(queryItem(id))?.title ?? 'Unknown Item'}'`, | |
| 87 | 104 | |
| 88 | // since the optimistic handler is perfect, there is no need | |
| 105 | // Since the optimistic handler is perfect, there is no need | |
| 89 | 106 | // to refetch any data once a success case is hit. |
| 90 | 107 | refetchOnSuccess: false, |
| 91 | 108 | }); |
| 92 | 109 | |
| 110 | // React example. Since `error` and `result` are not destructed, messages are | |
| 111 | // indicated through UI toasts from the mutation client. | |
| 93 | 112 | export function Example({ id }: { id: string }) { |
| 94 | 113 | const { data: list } = useSuspenseQuery(queryItemList); |
| 95 | const { run } = useMutation(mutDeleteItem); | |
| 114 | const { run } = useMutate(mutDeleteItem); | |
| 96 | 115 | |
| 97 | 116 | return list.map((id) => <li key={id}> |
| 98 | 117 | <Item id={id} /> |
| ... | ... | @@ -101,27 +120,25 @@ export function Example({ id }: { id: string }) { |
| 101 | 120 | } |
| 102 | 121 | ``` |
| 103 | 122 | |
| 104 | ### Batched Mutations | |
| 123 | ### Debounced Mutations | |
| 105 | 124 | |
| 106 | A batched mutation is defined with `mutations.defineBatched`. | |
| 125 | A debounced mutation is defined with `mutations.defineBatched`. | |
| 107 | 126 | |
| 108 | 127 | ```tsx |
| 109 | const mutSetItemName = mutationClient.defineBatched({ | |
| 110 | mode: "debounce", | |
| 111 | time: 200, | |
| 112 | ||
| 113 | // start by mutating the optimistic state | |
| 128 | const mutSetItemName = mutationClient.defineDebounced({ | |
| 129 | // Think of your mutator in terms of how it applies optimistic state. | |
| 114 | 130 | optimistic({ helpers }, id: string, name: string) { |
| 115 | 131 | helpers.objSet(queryItem(id), ["title"], name); |
| 116 | 132 | }, |
| 117 | // a value is snapshot before calling `optimistic` and after the | |
| 118 | // timer. if the snapshots differ, the `commit` function is called. | |
| 133 | // A value is snapshotted *before* calling `optimistic`, and then again after | |
| 134 | // the timer. If the snapshots differ, then `commit` function is called. | |
| 119 | 135 | getValue: ({ get }) => get(queryCounter)?.title ?? "", |
| 120 | 136 | |
| 121 | // batch the same `id`s together | |
| 137 | // Split different `id`s into their own debounces. | |
| 122 | 138 | key: ({ args: [id] }) => id, |
| 123 | 139 | |
| 124 | // commit the result to the backend | |
| 140 | // Commit the result to the backend. Here, you can observe the two snapshotted | |
| 141 | // values and form an API request. | |
| 125 | 142 | async commit({ initial, current, args: [id] }) { |
| 126 | 143 | const response = await fetch(`/items/${id}`, { |
| 127 | 144 | method: "patch", |
| ... | ... | @@ -130,6 +147,35 @@ const mutSetItemName = mutationClient.defineBatched({ |
| 130 | 147 | if (!response.ok) throw new Error(`HTTP ${response.status}`); |
| 131 | 148 | }, |
| 132 | 149 | |
| 133 | describe: ({ get }) => `rename '${get(queryItem())?.title ?? 'unknown'}'`, | |
| 150 | describe: ({ get, args: [id] }) => | |
| 151 | `Rename '${get(queryItem())?.title ?? 'Unknown Item'}'`, | |
| 152 | describeResult: ({ get, args: [id] }) => | |
| 153 | `Renamed '${get(queryItem(id))?.title ?? 'Unknown Item'}'`, | |
| 134 | 154 | }); |
| 155 | ||
| 156 | // React example. Since the error and result are read in this hook, | |
| 157 | // the success and failure states will be driven through the component UI. | |
| 158 | function Item({ id }: { id: string }) { | |
| 159 | const { data: item } = useSuspenseQuery(queryItem(id)); | |
| 160 | const { run, isSuccess, errorMessage } = useMutate(mutDeleteItem); | |
| 161 | ||
| 162 | // TODO: test this pattern. maybe introduce another hook for doing good input | |
| 163 | // fields that hook could also support an "Undo" button. | |
| 164 | return <> | |
| 165 | <input | |
| 166 | value={item.title} | |
| 167 | onChange={(e) => { | |
| 168 | run(e.target.value); | |
| 169 | }} | |
| 170 | /> | |
| 171 | { | |
| 172 | isSuccess | |
| 173 | ? "Saved" | |
| 174 | : errorMessage | |
| 175 | ? "Error: " + errorMessage : null | |
| 176 | } | |
| 177 | </> | |
| 178 | } | |
| 135 | 179 | ``` |
| 180 | ||
| 181 | ### |
src/batch.ts+47-5| ... | ... | @@ -23,7 +23,10 @@ export interface BatchMutationOptions< |
| 23 | 23 | */ |
| 24 | 24 | getValue: (context: Config["context"], ...args: Args) => Optimistic; |
| 25 | 25 | |
| 26 | mode: "debounce" | "throttle"; | |
| 26 | /** | |
| 27 | * @default "debounce" | |
| 28 | */ | |
| 29 | mode?: "debounce" | "throttle"; | |
| 27 | 30 | /** |
| 28 | 31 | * Milliseconds |
| 29 | 32 | * @default 200 |
| ... | ... | @@ -50,6 +53,17 @@ export interface BatchMutationOptions< |
| 50 | 53 | | (( |
| 51 | 54 | context: BatchCommitContext<NoInfer<Args>, Optimistic, Config>, |
| 52 | 55 | ) => string); |
| 56 | /** | |
| 57 | * Used in success messages. | |
| 58 | * Phrase it as a complete success message, e.g., "Renamed item successfully" | |
| 59 | * Set to null to suppress success reporting. | |
| 60 | */ | |
| 61 | describeResult?: | |
| 62 | | string | |
| 63 | | (( | |
| 64 | context: BatchCommitContext<NoInfer<Args>, Optimistic, Config> & { result: Result }, | |
| 65 | ) => string) | |
| 66 | | null; | |
| 53 | 67 | /** |
| 54 | 68 | * Refetch all of the data this mutation could have affected. |
| 55 | 69 | */ |
| ... | ... | @@ -97,6 +111,7 @@ interface BatchChannel<Args extends unknown[], Result, Optimistic> { |
| 97 | 111 | args: Args; |
| 98 | 112 | resolve: (result: Result) => void; |
| 99 | 113 | reject: (error: unknown) => void; |
| 114 | reportSuccessGlobally?: boolean; | |
| 100 | 115 | }>; |
| 101 | 116 | } |
| 102 | 117 | |
| ... | ... | @@ -197,15 +212,33 @@ export class BatchMutation< |
| 197 | 212 | return describe; |
| 198 | 213 | } |
| 199 | 214 | |
| 200 | /** Calling the mutation in a global scope. Errors are turned into UI toasts. */ | |
| 215 | describeResult(args: Args, initial: Optimistic, current: Optimistic, result: Result): string | undefined { | |
| 216 | const { describeResult } = this.#options; | |
| 217 | if (describeResult === null || describeResult === undefined) return undefined; | |
| 218 | return typeof describeResult === "function" | |
| 219 | ? describeResult({ | |
| 220 | ...this.#client.context, | |
| 221 | args, | |
| 222 | initial, | |
| 223 | current, | |
| 224 | result, | |
| 225 | }) | |
| 226 | : describeResult; | |
| 227 | } | |
| 228 | ||
| 229 | /** Calling the mutation in a global scope. Errors and successes are turned into UI toasts. */ | |
| 201 | 230 | run(...args: Args): void { |
| 202 | this.runAndReturn(...args).catch((error) => { | |
| 231 | this.#runAndReturn(args, true).catch((error) => { | |
| 203 | 232 | this.#client.reportError(error); |
| 204 | 233 | }); |
| 205 | 234 | } |
| 206 | 235 | |
| 207 | 236 | /** Calls the mutation, treating the errors as promise rejection. */ |
| 208 | 237 | runAndReturn(...args: Args): Promise<Result> { |
| 238 | return this.#runAndReturn(args, false); | |
| 239 | } | |
| 240 | ||
| 241 | #runAndReturn(args: Args, reportSuccessGlobally: boolean): Promise<Result> { | |
| 209 | 242 | const key = this.key(args); |
| 210 | 243 | const channel = this.#getOrPutChannel(key); |
| 211 | 244 | |
| ... | ... | @@ -260,7 +293,7 @@ export class BatchMutation< |
| 260 | 293 | |
| 261 | 294 | // Create promise for this caller |
| 262 | 295 | const { promise, resolve, reject } = Promise.withResolvers<Result>(); |
| 263 | channel.pending.push({ args, resolve, reject }); | |
| 296 | channel.pending.push({ args, resolve, reject, reportSuccessGlobally }); | |
| 264 | 297 | |
| 265 | 298 | // Set status to waiting and notify |
| 266 | 299 | if (channel.status === "idle") { |
| ... | ... | @@ -280,7 +313,7 @@ export class BatchMutation< |
| 280 | 313 | ) { |
| 281 | 314 | const time = this.#options.time ?? 200; |
| 282 | 315 | |
| 283 | if (this.#options.mode === "debounce") { | |
| 316 | if (this.#options.mode !== "throttle") { | |
| 284 | 317 | // Debounce: reset timer on each call |
| 285 | 318 | if (channel.timer !== null) { |
| 286 | 319 | clearTimeout(channel.timer); |
| ... | ... | @@ -364,6 +397,15 @@ export class BatchMutation< |
| 364 | 397 | // Resolve all pending promises |
| 365 | 398 | pendingItems.forEach(({ resolve }) => resolve(result)); |
| 366 | 399 | |
| 400 | // Report success globally if any of the pending items requested it | |
| 401 | const shouldReportSuccess = pendingItems.some((item) => item.reportSuccessGlobally); | |
| 402 | if (shouldReportSuccess) { | |
| 403 | const message = this.describeResult(firstArgs, initial, current, result); | |
| 404 | if (message && this.#client.reportSuccess) { | |
| 405 | this.#client.reportSuccess(message); | |
| 406 | } | |
| 407 | } | |
| 408 | ||
| 367 | 409 | // Record commit time for throttle mode |
| 368 | 410 | channel.lastCommitTime = Date.now(); |
| 369 | 411 |
src/client.ts+5-2| ... | ... | @@ -22,6 +22,7 @@ export interface MutationClientOptions< |
| 22 | 22 | events: OptimisticEvents, |
| 23 | 23 | ) => OptimisticHelpers; |
| 24 | 24 | reportError: (error: unknown) => void; |
| 25 | reportSuccess?: (message: string) => void; | |
| 25 | 26 | /** |
| 26 | 27 | * Compare two values for deep equality. Used by BatchMutation to determine |
| 27 | 28 | * if the optimistic state has changed from the initial snapshot. |
| ... | ... | @@ -42,12 +43,14 @@ export class MutationClient< |
| 42 | 43 | context: Context; |
| 43 | 44 | getOptimisticHelpers: (event: OptimisticEvents) => OptimisticHelpers; |
| 44 | 45 | reportError: (error: unknown) => void; |
| 46 | reportSuccess?: (message: string) => void; | |
| 45 | 47 | deepEquals: (a: unknown, b: unknown) => boolean; |
| 46 | 48 | |
| 47 | 49 | constructor(options: MutationClientOptions<Context, OptimisticHelpers>) { |
| 48 | 50 | this.context = options.context; |
| 49 | 51 | this.getOptimisticHelpers = options.getOptimisticHelpers; |
| 50 | 52 | this.reportError = options.reportError; |
| 53 | this.reportSuccess = options.reportSuccess; | |
| 51 | 54 | this.deepEquals = options.deepEquals ?? defaultDeepEquals; |
| 52 | 55 | } |
| 53 | 56 | |
| ... | ... | @@ -56,7 +59,7 @@ export class MutationClient< |
| 56 | 59 | * You press a button, a pending state appears, then it completes. This works |
| 57 | 60 | * great for forms, and is similar to React Query's mutation system. |
| 58 | 61 | */ |
| 59 | defineQueued<const Args extends unknown[], Result>( | |
| 62 | defineBlocking<const Args extends unknown[], Result>( | |
| 60 | 63 | options: MutationOptions< |
| 61 | 64 | Args, |
| 62 | 65 | Result, |
| ... | ... | @@ -77,7 +80,7 @@ export class MutationClient< |
| 77 | 80 | * works great for auto-saving input fields, follow buttons, and is preferred |
| 78 | 81 | * whenever possible. |
| 79 | 82 | */ |
| 80 | defineBatched<const Args extends unknown[], Result, Optimistic>( | |
| 83 | defineDebounced<const Args extends unknown[], Result, Optimistic>( | |
| 81 | 84 | options: BatchMutationOptions< |
| 82 | 85 | Args, |
| 83 | 86 | Result, |
src/mod.ts+6-6| ... | ... | @@ -14,10 +14,10 @@ export type { Mutation, MutationEvent } from "./types.ts"; |
| 14 | 14 | export { |
| 15 | 15 | createMutationButton, |
| 16 | 16 | type MutationButtonProps, |
| 17 | useMutation, | |
| 18 | type UseMutationError, | |
| 19 | type UseMutationIdle, | |
| 20 | type UseMutationResult, | |
| 21 | type UseMutationResultBase, | |
| 22 | type UseMutationSuccess, | |
| 17 | useMutate, | |
| 18 | type UseMutateError, | |
| 19 | type UseMutateIdle, | |
| 20 | type UseMutateResult, | |
| 21 | type UseMutateResultBase, | |
| 22 | type UseMutateSuccess, | |
| 23 | 23 | } from "./react.tsx"; |
src/queued.ts+26-3| ... | ... | @@ -19,13 +19,22 @@ export interface MutationOptions< |
| 19 | 19 | * params type is used to allow type inference. Place this function first to |
| 20 | 20 | * ensure TypeScript correctly infers the argument type for the rest of the |
| 21 | 21 | * functions. |
| 22 | * | |
| 23 | * In practice, optimistic context is never needed in this function, but it | |
| 24 | * is provided as the `this` value if you truly desire it. | |
| 22 | 25 | */ |
| 23 | mutate: (context: Config["context"], ...args: Args) => Promise<Result>; | |
| 26 | mutate: (this: Config["context"], ...args: Args) => Promise<Result>; | |
| 24 | 27 | /** |
| 25 | 28 | * Used in error messages and debug tools. |
| 26 | 29 | * Phrase it considering the template `Failed to ${describe(...)}` |
| 27 | 30 | */ |
| 28 | 31 | describe: string | ((context: Config["context"] & { args: Args }) => string); |
| 32 | /** | |
| 33 | * Used in success messages. | |
| 34 | * Phrase it as a complete success message, e.g., "Deleted item successfully" | |
| 35 | * Set to null to suppress success reporting. | |
| 36 | */ | |
| 37 | describeResult?: string | ((context: Config["context"] & { args: Args; result: Result }) => string) | null; | |
| 29 | 38 | /** |
| 30 | 39 | * Specifying the optimistic strategy is required. To disable, pass an empty |
| 31 | 40 | * function with a comment to document why it isn't needed. |
| ... | ... | @@ -33,6 +42,7 @@ export interface MutationOptions< |
| 33 | 42 | optimistic: (context: OptimisticContext<Args, Result, Config>) => void; |
| 34 | 43 | /** |
| 35 | 44 | * Refetch all of the data this mutation could have affected. |
| 45 | * Normally, optimistic helpers will perform | |
| 36 | 46 | * This is called automatically on errors. |
| 37 | 47 | */ |
| 38 | 48 | refetch?: (context: Config["context"] & { args: Args }) => Promise<void>; |
| ... | ... | @@ -154,9 +164,22 @@ export class QueuedMutation< |
| 154 | 164 | : describe; |
| 155 | 165 | } |
| 156 | 166 | |
| 167 | describeResult(args: Args, result: Result): string | undefined { | |
| 168 | const { describeResult } = this.#options; | |
| 169 | if (describeResult === null || describeResult === undefined) return undefined; | |
| 170 | return typeof describeResult === "function" | |
| 171 | ? describeResult({ ...this.#client.context, args, result }) | |
| 172 | : describeResult; | |
| 173 | } | |
| 174 | ||
| 157 | 175 | /** Calling the mutation in a global scope. Errors are turned into UI toasts. */ |
| 158 | 176 | run(...args: Args) { |
| 159 | this.runAndReturn(...args).catch((error) => { | |
| 177 | this.runAndReturn(...args).then((result) => { | |
| 178 | const message = this.describeResult(args, result); | |
| 179 | if (message && this.#client.reportSuccess) { | |
| 180 | this.#client.reportSuccess(message); | |
| 181 | } | |
| 182 | }).catch((error) => { | |
| 160 | 183 | this.#client.reportError(error); |
| 161 | 184 | }); |
| 162 | 185 | } |
| ... | ... | @@ -244,7 +267,7 @@ export class QueuedMutation< |
| 244 | 267 | channel.status = "mutating"; |
| 245 | 268 | this.#notify(channel, "mutating"); |
| 246 | 269 | |
| 247 | this.#options.mutate(this.#client.context, ...args).then((result) => { | |
| 270 | this.#options.mutate.call(this.#client.context, ...args).then((result) => { | |
| 248 | 271 | // remove rollbacks and apply optimistic success handlers |
| 249 | 272 | channel.rollbacks.splice(0, item.rollbacks); |
| 250 | 273 | onSuccess.forEach((cb) => cb(result)); |
src/react.tsx+24-21| ... | ... | @@ -13,12 +13,12 @@ import type { Mutation } from "./types.ts"; |
| 13 | 13 | * Subscribe to a mutation's status, as well as accessing a local `run` method. |
| 14 | 14 | * The resulting mutation can be used directly or passed to a {@link createMutationButton|mutation button}. |
| 15 | 15 | */ |
| 16 | export function useMutation< | |
| 16 | export function useMutate< | |
| 17 | 17 | Args extends unknown[], |
| 18 | 18 | Result, |
| 19 | 19 | >( |
| 20 | 20 | mutation: Mutation<Args, Result> | null, |
| 21 | ): UseMutationResult<Args, Result> { | |
| 21 | ): UseMutateResult<Args, Result> { | |
| 22 | 22 | const [_, setRerender] = useState(0); |
| 23 | 23 | const [observer] = useState(() => new Observer<Args, Result>(setRerender)); |
| 24 | 24 | useEffect(() => () => void observer.reset(), []); |
| ... | ... | @@ -29,20 +29,20 @@ export function useMutation< |
| 29 | 29 | return observer.binding; |
| 30 | 30 | } |
| 31 | 31 | |
| 32 | export type UseMutationResult<Args extends unknown[], Result> = | |
| 33 | & UseMutationResultBase<Args> | |
| 32 | export type UseMutateResult<Args extends unknown[], Result> = | |
| 33 | & UseMutateResultBase<Args> | |
| 34 | 34 | & ( |
| 35 | | UseMutationSuccess<Result> | |
| 36 | | UseMutationError | |
| 37 | | UseMutationIdle | |
| 35 | | UseMutateSuccess<Result> | |
| 36 | | UseMutateError | |
| 37 | | UseMutateIdle | |
| 38 | 38 | ); |
| 39 | 39 | |
| 40 | export interface UseMutationResultBase<Args extends unknown[]> { | |
| 40 | export interface UseMutateResultBase<Args extends unknown[]> { | |
| 41 | 41 | run: (...args: Args) => void; |
| 42 | 42 | clear: () => void; |
| 43 | 43 | } |
| 44 | 44 | |
| 45 | export interface UseMutationSuccess<Result> { | |
| 45 | export interface UseMutateSuccess<Result> { | |
| 46 | 46 | status: "success"; |
| 47 | 47 | result: Result; |
| 48 | 48 | error: undefined; |
| ... | ... | @@ -57,7 +57,7 @@ export interface UseMutationSuccess<Result> { |
| 57 | 57 | /** `true` when there is optimistic state applied. */ |
| 58 | 58 | isOptimisticData: boolean; |
| 59 | 59 | } |
| 60 | export interface UseMutationError { | |
| 60 | export interface UseMutateError { | |
| 61 | 61 | status: "error"; |
| 62 | 62 | result: undefined; |
| 63 | 63 | error: unknown; |
| ... | ... | @@ -72,7 +72,7 @@ export interface UseMutationError { |
| 72 | 72 | /** `true` when there is optimistic state applied. */ |
| 73 | 73 | isOptimisticData: boolean; |
| 74 | 74 | } |
| 75 | export interface UseMutationIdle { | |
| 75 | export interface UseMutateIdle { | |
| 76 | 76 | status: "idle" | "mutating"; |
| 77 | 77 | result: undefined; |
| 78 | 78 | error: undefined; |
| ... | ... | @@ -90,7 +90,7 @@ export interface UseMutationIdle { |
| 90 | 90 | |
| 91 | 91 | type AnyMutationState<Result> = |
| 92 | 92 | & Omit< |
| 93 | UseMutationIdle, | |
| 93 | UseMutateIdle, | |
| 94 | 94 | "status" | "result" | "error" | "isSuccess" | "isError" |
| 95 | 95 | > |
| 96 | 96 | & { |
| ... | ... | @@ -147,7 +147,7 @@ class Observer<Args extends unknown[], Result> { |
| 147 | 147 | this.state = initialState(); |
| 148 | 148 | } |
| 149 | 149 | |
| 150 | binding: UseMutationResult<Args, Result> = ((self: this) => ({ | |
| 150 | binding: UseMutateResult<Args, Result> = ((self: this) => ({ | |
| 151 | 151 | run(...args: Args) { |
| 152 | 152 | const mutation = self.mutation; |
| 153 | 153 | if (!mutation) return; |
| ... | ... | @@ -189,10 +189,13 @@ class Observer<Args extends unknown[], Result> { |
| 189 | 189 | }, |
| 190 | 190 | ); |
| 191 | 191 | } |
| 192 | // use global error handling if this usage of the hook doesnt check for | |
| 193 | // errors this makes it act pretty awesome in terms of defaults. you don't | |
| 194 | // have to worry about the errors, they'll surface exactly once. | |
| 195 | if (self.watched.has("isError") || self.watched.has("error")) { | |
| 192 | // use global error/success handling if this usage of the hook doesn't check for | |
| 193 | // errors or success. This makes it act pretty awesome in terms of defaults. | |
| 194 | // You don't have to worry about the errors/successes, they'll surface exactly once. | |
| 195 | if ( | |
| 196 | self.watched.has("isError") || self.watched.has("error") || | |
| 197 | self.watched.has("isSuccess") || self.watched.has("result") | |
| 198 | ) { | |
| 196 | 199 | mutation.runAndReturn(...args).catch(() => { |
| 197 | 200 | // caught in event listener |
| 198 | 201 | }); |
| ... | ... | @@ -243,7 +246,7 @@ class Observer<Args extends unknown[], Result> { |
| 243 | 246 | self.watched.add("isOptimisticData"); |
| 244 | 247 | return self.state.isOptimisticData; |
| 245 | 248 | }, |
| 246 | } as UseMutationResult<Args, Result>))(this); | |
| 249 | } as UseMutateResult<Args, Result>))(this); | |
| 247 | 250 | } |
| 248 | 251 | |
| 249 | 252 | interface BaseButtonProps { |
| ... | ... | @@ -263,7 +266,7 @@ interface MutationButtonComponent<Props> { |
| 263 | 266 | export interface MutationButtonProps<Args extends unknown[], Result> { |
| 264 | 267 | mutation: |
| 265 | 268 | | Mutation<Args, Result> |
| 266 | | Pick<UseMutationResult<Args, Result>, "run" | "status" | "isPending">; | |
| 269 | | Pick<UseMutateResult<Args, Result>, "run" | "status" | "isPending">; | |
| 267 | 270 | /** Preventing default will interrupt the mutation */ |
| 268 | 271 | args: Args | ((e: MouseEvent) => Args | null); |
| 269 | 272 | /** Preventing default will interrupt the mutation */ |
| ... | ... | @@ -274,7 +277,7 @@ export interface MutationButtonProps<Args extends unknown[], Result> { |
| 274 | 277 | * Wraps a custom button component with logic to execute a mutation. The wrapped |
| 275 | 278 | * component must accept `onClick` and an `isPending` property. When the inner |
| 276 | 279 | * component emits `onClick`, that will begin the mutation. This is a trival |
| 277 | * abstraction on top of `useMutation`, but with type gymnastics to allow safe | |
| 280 | * abstraction on top of `useMutate`, but with type gymnastics to allow safe | |
| 278 | 281 | * types. |
| 279 | 282 | */ |
| 280 | 283 | export function createMutationButton<Props>( |
| ... | ... | @@ -315,7 +318,7 @@ function GenericMutationButton< |
| 315 | 318 | const { mutation, args, onClick, ...forwarded } = props; |
| 316 | 319 | forwarded satisfies Omit<Props, keyof MutationButtonProps<Args, Result>>; |
| 317 | 320 | |
| 318 | const localHook = useMutation("subscribe" in mutation ? mutation : null); | |
| 321 | const localHook = useMutate("subscribe" in mutation ? mutation : null); | |
| 319 | 322 | const state = "subscribe" in mutation ? localHook : mutation; |
| 320 | 323 | |
| 321 | 324 | return ( |
test/batch.test.ts+30-28| ... | ... | @@ -65,7 +65,7 @@ test("BatchMutation - basic mutation success with debounce", async () => { |
| 65 | 65 | let commitCallCount = 0; |
| 66 | 66 | let refetchCallCount = 0; |
| 67 | 67 | |
| 68 | const mutation = client.defineBatched({ | |
| 68 | const mutation = client.defineDebounced({ | |
| 69 | 69 | optimistic({ helpers }, amount: number) { |
| 70 | 70 | helpers.increment("counter", amount); |
| 71 | 71 | }, |
| ... | ... | @@ -98,7 +98,7 @@ test("BatchMutation - run() catches errors", async () => { |
| 98 | 98 | testStore.clear(); |
| 99 | 99 | testStore.set("counter", 0); |
| 100 | 100 | |
| 101 | const mutation = client.defineBatched({ | |
| 101 | const mutation = client.defineDebounced({ | |
| 102 | 102 | optimistic({ helpers }, amount: number) { |
| 103 | 103 | helpers.increment("counter", amount); |
| 104 | 104 | }, |
| ... | ... | @@ -125,7 +125,7 @@ test("BatchMutation - runAndReturn() rejects on error", async () => { |
| 125 | 125 | testStore.clear(); |
| 126 | 126 | testStore.set("counter", 0); |
| 127 | 127 | |
| 128 | const mutation = client.defineBatched({ | |
| 128 | const mutation = client.defineDebounced({ | |
| 129 | 129 | optimistic({ helpers }, amount: number) { |
| 130 | 130 | helpers.increment("counter", amount); |
| 131 | 131 | }, |
| ... | ... | @@ -159,7 +159,7 @@ test("BatchMutation - debounce batches rapid calls", async () => { |
| 159 | 159 | let commitCallCount = 0; |
| 160 | 160 | const commitArgs: Array<{ initial: number; current: number }> = []; |
| 161 | 161 | |
| 162 | const mutation = client.defineBatched({ | |
| 162 | const mutation = client.defineDebounced({ | |
| 163 | 163 | optimistic({ helpers }, amount: number) { |
| 164 | 164 | helpers.increment("counter", amount); |
| 165 | 165 | }, |
| ... | ... | @@ -201,7 +201,7 @@ test("BatchMutation - debounce resets timer on each call", async () => { |
| 201 | 201 | |
| 202 | 202 | let commitCallCount = 0; |
| 203 | 203 | |
| 204 | const mutation = client.defineBatched({ | |
| 204 | const mutation = client.defineDebounced({ | |
| 205 | 205 | optimistic({ helpers }, amount: number) { |
| 206 | 206 | helpers.increment("counter", amount); |
| 207 | 207 | }, |
| ... | ... | @@ -250,7 +250,7 @@ test("BatchMutation - debounce separates batches after timeout", async () => { |
| 250 | 250 | let commitCallCount = 0; |
| 251 | 251 | const commitArgs: Array<{ initial: number; current: number }> = []; |
| 252 | 252 | |
| 253 | const mutation = client.defineBatched({ | |
| 253 | const mutation = client.defineDebounced({ | |
| 254 | 254 | optimistic({ helpers }, amount: number) { |
| 255 | 255 | helpers.increment("counter", amount); |
| 256 | 256 | }, |
| ... | ... | @@ -295,7 +295,7 @@ test("BatchMutation - throttle commits immediately on first call", async () => { |
| 295 | 295 | let commitTime = 0; |
| 296 | 296 | const startTime = Date.now(); |
| 297 | 297 | |
| 298 | const mutation = client.defineBatched({ | |
| 298 | const mutation = client.defineDebounced({ | |
| 299 | 299 | optimistic({ helpers }, amount: number) { |
| 300 | 300 | helpers.increment("counter", amount); |
| 301 | 301 | }, |
| ... | ... | @@ -325,7 +325,7 @@ test("BatchMutation - throttle batches calls within time window", async () => { |
| 325 | 325 | let commitCallCount = 0; |
| 326 | 326 | const commitArgs: Array<{ initial: number; current: number }> = []; |
| 327 | 327 | |
| 328 | const mutation = client.defineBatched({ | |
| 328 | const mutation = client.defineDebounced({ | |
| 329 | 329 | optimistic({ helpers }, amount: number) { |
| 330 | 330 | helpers.increment("counter", amount); |
| 331 | 331 | }, |
| ... | ... | @@ -377,7 +377,7 @@ test("BatchMutation - throttle allows new batch after time window", async () => |
| 377 | 377 | |
| 378 | 378 | let commitCallCount = 0; |
| 379 | 379 | |
| 380 | const mutation = client.defineBatched({ | |
| 380 | const mutation = client.defineDebounced({ | |
| 381 | 381 | optimistic({ helpers }, amount: number) { |
| 382 | 382 | helpers.increment("counter", amount); |
| 383 | 383 | }, |
| ... | ... | @@ -420,7 +420,7 @@ test("BatchMutation - skips commit when value unchanged", async () => { |
| 420 | 420 | |
| 421 | 421 | let commitCallCount = 0; |
| 422 | 422 | |
| 423 | const mutation = client.defineBatched({ | |
| 423 | const mutation = client.defineDebounced({ | |
| 424 | 424 | optimistic({ helpers }, amount: number) { |
| 425 | 425 | helpers.increment("counter", amount); |
| 426 | 426 | }, |
| ... | ... | @@ -479,7 +479,7 @@ test("BatchMutation - uses deepEquals for comparison", async () => { |
| 479 | 479 | |
| 480 | 480 | let commitCallCount = 0; |
| 481 | 481 | |
| 482 | const mutation = client.defineBatched({ | |
| 482 | const mutation = client.defineDebounced({ | |
| 483 | 483 | optimistic({ helpers }, count: number) { |
| 484 | 484 | helpers.setCount(count); |
| 485 | 485 | }, |
| ... | ... | @@ -531,7 +531,7 @@ test("BatchMutation - custom deepEquals function", async () => { |
| 531 | 531 | testStore.clear(); |
| 532 | 532 | testStore.set("counter", 0); |
| 533 | 533 | |
| 534 | const mutation = client.defineBatched({ | |
| 534 | const mutation = client.defineDebounced({ | |
| 535 | 535 | optimistic({ helpers }, amount: number) { |
| 536 | 536 | helpers.increment("counter", amount); |
| 537 | 537 | }, |
| ... | ... | @@ -546,7 +546,9 @@ test("BatchMutation - custom deepEquals function", async () => { |
| 546 | 546 | async refetch() {}, |
| 547 | 547 | }); |
| 548 | 548 | |
| 549 | await mutation.runAndReturn(5); | |
| 549 | await mutation.runAndReturn(5).catch(() => { | |
| 550 | // Expected to fail due to commit error | |
| 551 | }); | |
| 550 | 552 | await delay(30); |
| 551 | 553 | |
| 552 | 554 | // Custom deepEquals should have been called |
| ... | ... | @@ -562,7 +564,7 @@ test("BatchMutation - rollback on commit error", async () => { |
| 562 | 564 | testStore.clear(); |
| 563 | 565 | testStore.set("counter", 10); |
| 564 | 566 | |
| 565 | const mutation = client.defineBatched({ | |
| 567 | const mutation = client.defineDebounced({ | |
| 566 | 568 | optimistic({ helpers }, amount: number) { |
| 567 | 569 | helpers.increment("counter", amount); |
| 568 | 570 | }, |
| ... | ... | @@ -594,7 +596,7 @@ test("BatchMutation - error event includes error details", async () => { |
| 594 | 596 | |
| 595 | 597 | const tracker = createEventTracker<number>(); |
| 596 | 598 | |
| 597 | const mutation = client.defineBatched({ | |
| 599 | const mutation = client.defineDebounced({ | |
| 598 | 600 | optimistic({ helpers }, amount: number) { |
| 599 | 601 | helpers.increment("counter", amount); |
| 600 | 602 | }, |
| ... | ... | @@ -629,7 +631,7 @@ test("BatchMutation - key() returns JSON stringified key", () => { |
| 629 | 631 | const { client } = createTestClient(); |
| 630 | 632 | testStore.clear(); |
| 631 | 633 | |
| 632 | const mutation = client.defineBatched({ | |
| 634 | const mutation = client.defineDebounced({ | |
| 633 | 635 | optimistic(_ctx, _id: string) {}, |
| 634 | 636 | mode: "debounce", |
| 635 | 637 | time: 20, |
| ... | ... | @@ -649,7 +651,7 @@ test("BatchMutation - key() can return array", () => { |
| 649 | 651 | const { client } = createTestClient(); |
| 650 | 652 | testStore.clear(); |
| 651 | 653 | |
| 652 | const mutation = client.defineBatched({ | |
| 654 | const mutation = client.defineDebounced({ | |
| 653 | 655 | optimistic(_ctx, _id: string) {}, |
| 654 | 656 | mode: "debounce", |
| 655 | 657 | time: 20, |
| ... | ... | @@ -676,7 +678,7 @@ test("BatchMutation - different keys create separate batches", async () => { |
| 676 | 678 | |
| 677 | 679 | let commitCallCount = 0; |
| 678 | 680 | |
| 679 | const mutation = client.defineBatched({ | |
| 681 | const mutation = client.defineDebounced({ | |
| 680 | 682 | optimistic({ helpers }, key: string, amount: number) { |
| 681 | 683 | helpers.increment(`counter-${key}`, amount); |
| 682 | 684 | }, |
| ... | ... | @@ -713,7 +715,7 @@ test("BatchMutation - describe() with string", () => { |
| 713 | 715 | const { client } = createTestClient(); |
| 714 | 716 | testStore.clear(); |
| 715 | 717 | |
| 716 | const mutation = client.defineBatched({ | |
| 718 | const mutation = client.defineDebounced({ | |
| 717 | 719 | optimistic(_ctx, _amount: number) {}, |
| 718 | 720 | mode: "debounce", |
| 719 | 721 | time: 20, |
| ... | ... | @@ -733,7 +735,7 @@ test("BatchMutation - describe() with function", () => { |
| 733 | 735 | const { client } = createTestClient(); |
| 734 | 736 | testStore.clear(); |
| 735 | 737 | |
| 736 | const mutation = client.defineBatched({ | |
| 738 | const mutation = client.defineDebounced({ | |
| 737 | 739 | optimistic(_ctx, _amount: number) {}, |
| 738 | 740 | mode: "debounce", |
| 739 | 741 | time: 20, |
| ... | ... | @@ -758,7 +760,7 @@ test("BatchMutation - all pending promises resolve with same result", async () = |
| 758 | 760 | testStore.clear(); |
| 759 | 761 | testStore.set("counter", 0); |
| 760 | 762 | |
| 761 | const mutation = client.defineBatched({ | |
| 763 | const mutation = client.defineDebounced({ | |
| 762 | 764 | optimistic({ helpers }, amount: number) { |
| 763 | 765 | helpers.increment("counter", amount); |
| 764 | 766 | }, |
| ... | ... | @@ -794,7 +796,7 @@ test("BatchMutation - all pending promises reject with same error", async () => |
| 794 | 796 | testStore.clear(); |
| 795 | 797 | testStore.set("counter", 0); |
| 796 | 798 | |
| 797 | const mutation = client.defineBatched({ | |
| 799 | const mutation = client.defineDebounced({ | |
| 798 | 800 | optimistic({ helpers }, amount: number) { |
| 799 | 801 | helpers.increment("counter", amount); |
| 800 | 802 | }, |
| ... | ... | @@ -837,7 +839,7 @@ test("BatchMutation - handles empty getValue result", async () => { |
| 837 | 839 | |
| 838 | 840 | let commitCallCount = 0; |
| 839 | 841 | |
| 840 | const mutation = client.defineBatched({ | |
| 842 | const mutation = client.defineDebounced({ | |
| 841 | 843 | optimistic({ helpers }, amount: number) { |
| 842 | 844 | helpers.setValue("nonexistent", amount); |
| 843 | 845 | }, |
| ... | ... | @@ -865,7 +867,7 @@ test("BatchMutation - channel cleanup after idle with no listeners", async () => |
| 865 | 867 | testStore.clear(); |
| 866 | 868 | testStore.set("counter", 0); |
| 867 | 869 | |
| 868 | const mutation = client.defineBatched({ | |
| 870 | const mutation = client.defineDebounced({ | |
| 869 | 871 | optimistic({ helpers }, amount: number) { |
| 870 | 872 | helpers.increment("counter", amount); |
| 871 | 873 | }, |
| ... | ... | @@ -900,7 +902,7 @@ test("BatchMutation - default time is 200ms", async () => { |
| 900 | 902 | let commitTime: number | null = null; |
| 901 | 903 | const startTime = Date.now(); |
| 902 | 904 | |
| 903 | const mutation = client.defineBatched({ | |
| 905 | const mutation = client.defineDebounced({ | |
| 904 | 906 | optimistic({ helpers }, amount: number) { |
| 905 | 907 | helpers.increment("counter", amount); |
| 906 | 908 | }, |
| ... | ... | @@ -931,7 +933,7 @@ test("BatchMutation - context is passed to getValue", async () => { |
| 931 | 933 | |
| 932 | 934 | let receivedUserId: string | undefined; |
| 933 | 935 | |
| 934 | const mutation = client.defineBatched({ | |
| 936 | const mutation = client.defineDebounced({ | |
| 935 | 937 | optimistic({ helpers }, amount: number) { |
| 936 | 938 | helpers.increment("counter", amount); |
| 937 | 939 | }, |
| ... | ... | @@ -962,7 +964,7 @@ test("BatchMutation - context is passed to commit", async () => { |
| 962 | 964 | |
| 963 | 965 | let receivedUserId: string | undefined; |
| 964 | 966 | |
| 965 | const mutation = client.defineBatched({ | |
| 967 | const mutation = client.defineDebounced({ | |
| 966 | 968 | optimistic({ helpers }, amount: number) { |
| 967 | 969 | helpers.increment("counter", amount); |
| 968 | 970 | }, |
| ... | ... | @@ -991,7 +993,7 @@ test("BatchMutation - first args are used for commit", async () => { |
| 991 | 993 | |
| 992 | 994 | let receivedArgs: [string, number] | undefined; |
| 993 | 995 | |
| 994 | const mutation = client.defineBatched({ | |
| 996 | const mutation = client.defineDebounced({ | |
| 995 | 997 | optimistic({ helpers }, _label: string, amount: number) { |
| 996 | 998 | helpers.increment("counter", amount); |
| 997 | 999 | }, |
test/queued.test.ts+74-74| ... | ... | @@ -45,8 +45,8 @@ test("QueuedMutation - basic mutation success", async () => { |
| 45 | 45 | let mutateCallCount = 0; |
| 46 | 46 | let refetchCallCount = 0; |
| 47 | 47 | |
| 48 | const mutation = client.defineQueued({ | |
| 49 | async mutate(_, value: string) { | |
| 48 | const mutation = client.defineBlocking({ | |
| 49 | async mutate(value: string) { | |
| 50 | 50 | mutateCallCount++; |
| 51 | 51 | await delay(10); |
| 52 | 52 | return `result-${value}`; |
| ... | ... | @@ -73,8 +73,8 @@ test("QueuedMutation - basic mutation success", async () => { |
| 73 | 73 | test("QueuedMutation - run() catches errors", async () => { |
| 74 | 74 | const { client, errors } = createTestClient(); |
| 75 | 75 | |
| 76 | const mutation = client.defineQueued({ | |
| 77 | async mutate(_, _value: string) { | |
| 76 | const mutation = client.defineBlocking({ | |
| 77 | async mutate(_value: string) { | |
| 78 | 78 | throw new Error("mutation failed"); |
| 79 | 79 | }, |
| 80 | 80 | describe: "failing mutation", |
| ... | ... | @@ -92,8 +92,8 @@ test("QueuedMutation - run() catches errors", async () => { |
| 92 | 92 | test("QueuedMutation - runAndReturn() rejects on error", async () => { |
| 93 | 93 | const { client } = createTestClient(); |
| 94 | 94 | |
| 95 | const mutation = client.defineQueued({ | |
| 96 | async mutate(_, _value: string) { | |
| 95 | const mutation = client.defineBlocking({ | |
| 96 | async mutate(_value: string) { | |
| 97 | 97 | throw new Error("mutation failed"); |
| 98 | 98 | }, |
| 99 | 99 | describe: "failing mutation", |
| ... | ... | @@ -112,8 +112,8 @@ test("QueuedMutation - optimistic updates are applied immediately", async () => |
| 112 | 112 | const { client } = createTestClient(); |
| 113 | 113 | testStore.clear(); |
| 114 | 114 | |
| 115 | const mutation = client.defineQueued({ | |
| 116 | async mutate(_, _key: string, value: string) { | |
| 115 | const mutation = client.defineBlocking({ | |
| 116 | async mutate(_key: string, value: string) { | |
| 117 | 117 | await delay(50); |
| 118 | 118 | return value; |
| 119 | 119 | }, |
| ... | ... | @@ -139,8 +139,8 @@ test("QueuedMutation - rollback on error", async () => { |
| 139 | 139 | const { client } = createTestClient(); |
| 140 | 140 | testStore.clear(); |
| 141 | 141 | |
| 142 | const mutation = client.defineQueued({ | |
| 143 | async mutate(_, _key: string, _value: string) { | |
| 142 | const mutation = client.defineBlocking({ | |
| 143 | async mutate(_key: string, _value: string) { | |
| 144 | 144 | await delay(10); |
| 145 | 145 | throw new Error("mutation failed"); |
| 146 | 146 | }, |
| ... | ... | @@ -162,8 +162,8 @@ test("QueuedMutation - onSuccess callback is called", async () => { |
| 162 | 162 | const { client } = createTestClient(); |
| 163 | 163 | const successResults: string[] = []; |
| 164 | 164 | |
| 165 | const mutation = client.defineQueued({ | |
| 166 | async mutate(_, value: string) { | |
| 165 | const mutation = client.defineBlocking({ | |
| 166 | async mutate(value: string) { | |
| 167 | 167 | return `result-${value}`; |
| 168 | 168 | }, |
| 169 | 169 | describe: "test mutation", |
| ... | ... | @@ -184,8 +184,8 @@ test("QueuedMutation - mutations with same key execute serially", async () => { |
| 184 | 184 | const { client } = createTestClient(); |
| 185 | 185 | const executionOrder: string[] = []; |
| 186 | 186 | |
| 187 | const mutation = client.defineQueued({ | |
| 188 | async mutate(_, id: string) { | |
| 187 | const mutation = client.defineBlocking({ | |
| 188 | async mutate(id: string) { | |
| 189 | 189 | executionOrder.push(`start-${id}`); |
| 190 | 190 | await delay(20); |
| 191 | 191 | executionOrder.push(`end-${id}`); |
| ... | ... | @@ -215,8 +215,8 @@ test("QueuedMutation - mutations with different keys execute in parallel", async |
| 215 | 215 | const { client } = createTestClient(); |
| 216 | 216 | const executionOrder: string[] = []; |
| 217 | 217 | |
| 218 | const mutation = client.defineQueued({ | |
| 219 | async mutate(_, id: string) { | |
| 218 | const mutation = client.defineBlocking({ | |
| 219 | async mutate(id: string) { | |
| 220 | 220 | executionOrder.push(`start-${id}`); |
| 221 | 221 | await delay(20); |
| 222 | 222 | executionOrder.push(`end-${id}`); |
| ... | ... | @@ -244,8 +244,8 @@ test("QueuedMutation - mutations with different keys execute in parallel", async |
| 244 | 244 | test("QueuedMutation - key() returns JSON stringified key", () => { |
| 245 | 245 | const { client } = createTestClient(); |
| 246 | 246 | |
| 247 | const mutation = client.defineQueued({ | |
| 248 | async mutate(_, id: string) { | |
| 247 | const mutation = client.defineBlocking({ | |
| 248 | async mutate(id: string) { | |
| 249 | 249 | return id; |
| 250 | 250 | }, |
| 251 | 251 | describe: "test mutation", |
| ... | ... | @@ -263,8 +263,8 @@ test("QueuedMutation - key() returns JSON stringified key", () => { |
| 263 | 263 | test("QueuedMutation - key() defaults to 'shared' when no key function", () => { |
| 264 | 264 | const { client } = createTestClient(); |
| 265 | 265 | |
| 266 | const mutation = client.defineQueued({ | |
| 267 | async mutate(_, id: string) { | |
| 266 | const mutation = client.defineBlocking({ | |
| 267 | async mutate(id: string) { | |
| 268 | 268 | return id; |
| 269 | 269 | }, |
| 270 | 270 | describe: "test mutation", |
| ... | ... | @@ -278,8 +278,8 @@ test("QueuedMutation - key() defaults to 'shared' when no key function", () => { |
| 278 | 278 | test("QueuedMutation - key() can return array", () => { |
| 279 | 279 | const { client } = createTestClient(); |
| 280 | 280 | |
| 281 | const mutation = client.defineQueued({ | |
| 282 | async mutate(_, _userId: string, _itemId: string) { | |
| 281 | const mutation = client.defineBlocking({ | |
| 282 | async mutate(_userId: string, _itemId: string) { | |
| 283 | 283 | return "result"; |
| 284 | 284 | }, |
| 285 | 285 | describe: "test mutation", |
| ... | ... | @@ -300,8 +300,8 @@ test("QueuedMutation - key() can return array", () => { |
| 300 | 300 | test("QueuedMutation - describe() with string", () => { |
| 301 | 301 | const { client } = createTestClient(); |
| 302 | 302 | |
| 303 | const mutation = client.defineQueued({ | |
| 304 | async mutate(_, value: string) { | |
| 303 | const mutation = client.defineBlocking({ | |
| 304 | async mutate(value: string) { | |
| 305 | 305 | return value; |
| 306 | 306 | }, |
| 307 | 307 | describe: "create item", |
| ... | ... | @@ -315,8 +315,8 @@ test("QueuedMutation - describe() with string", () => { |
| 315 | 315 | test("QueuedMutation - describe() with function", () => { |
| 316 | 316 | const { client } = createTestClient(); |
| 317 | 317 | |
| 318 | const mutation = client.defineQueued({ | |
| 319 | async mutate(_, id: string) { | |
| 318 | const mutation = client.defineBlocking({ | |
| 319 | async mutate(id: string) { | |
| 320 | 320 | return id; |
| 321 | 321 | }, |
| 322 | 322 | describe({ args }) { |
| ... | ... | @@ -333,8 +333,8 @@ test("QueuedMutation - describe() with function", () => { |
| 333 | 333 | test("QueuedMutation - describe() receives context", () => { |
| 334 | 334 | const { client } = createTestClient(); |
| 335 | 335 | |
| 336 | const mutation = client.defineQueued({ | |
| 337 | async mutate(_, id: string) { | |
| 336 | const mutation = client.defineBlocking({ | |
| 337 | async mutate(id: string) { | |
| 338 | 338 | return id; |
| 339 | 339 | }, |
| 340 | 340 | describe({ userId, args }) { |
| ... | ... | @@ -355,8 +355,8 @@ test("QueuedMutation - subscribe() tracks mutation events", async () => { |
| 355 | 355 | const { client } = createTestClient(); |
| 356 | 356 | const tracker = createEventTracker<string>(); |
| 357 | 357 | |
| 358 | const mutation = client.defineQueued({ | |
| 359 | async mutate(_, value: string) { | |
| 358 | const mutation = client.defineBlocking({ | |
| 359 | async mutate(value: string) { | |
| 360 | 360 | await delay(10); |
| 361 | 361 | return `result-${value}`; |
| 362 | 362 | }, |
| ... | ... | @@ -384,8 +384,8 @@ test("QueuedMutation - unsubscribe stops receiving events", async () => { |
| 384 | 384 | const { client } = createTestClient(); |
| 385 | 385 | const tracker = createEventTracker<string>(); |
| 386 | 386 | |
| 387 | const mutation = client.defineQueued({ | |
| 388 | async mutate(_, value: string) { | |
| 387 | const mutation = client.defineBlocking({ | |
| 388 | async mutate(value: string) { | |
| 389 | 389 | await delay(10); |
| 390 | 390 | return value; |
| 391 | 391 | }, |
| ... | ... | @@ -411,8 +411,8 @@ test("QueuedMutation - refetchOnSuccess can be disabled", async () => { |
| 411 | 411 | const { client } = createTestClient(); |
| 412 | 412 | let refetchCallCount = 0; |
| 413 | 413 | |
| 414 | const mutation = client.defineQueued({ | |
| 415 | async mutate(_, _value: string) { | |
| 414 | const mutation = client.defineBlocking({ | |
| 415 | async mutate(_value: string) { | |
| 416 | 416 | return _value; |
| 417 | 417 | }, |
| 418 | 418 | describe: "test mutation", |
| ... | ... | @@ -432,8 +432,8 @@ test("QueuedMutation - refetch is called on error", async () => { |
| 432 | 432 | const { client } = createTestClient(); |
| 433 | 433 | let refetchCallCount = 0; |
| 434 | 434 | |
| 435 | const mutation = client.defineQueued({ | |
| 436 | async mutate(_, _value: string) { | |
| 435 | const mutation = client.defineBlocking({ | |
| 436 | async mutate(_value: string) { | |
| 437 | 437 | throw new Error("mutation failed"); |
| 438 | 438 | }, |
| 439 | 439 | describe: "failing mutation", |
| ... | ... | @@ -452,8 +452,8 @@ test("QueuedMutation - queued mutations are cancelled on error", async () => { |
| 452 | 452 | const { client } = createTestClient(); |
| 453 | 453 | const executionOrder: string[] = []; |
| 454 | 454 | |
| 455 | const mutation = client.defineQueued({ | |
| 456 | async mutate(_, id: string) { | |
| 455 | const mutation = client.defineBlocking({ | |
| 456 | async mutate(id: string) { | |
| 457 | 457 | executionOrder.push(`start-${id}`); |
| 458 | 458 | await delay(10); |
| 459 | 459 | if (id === "1") { |
| ... | ... | @@ -486,8 +486,8 @@ test("QueuedMutation - rollbacks are called in reverse order on error", async () |
| 486 | 486 | const { client } = createTestClient(); |
| 487 | 487 | const rollbackOrder: number[] = []; |
| 488 | 488 | |
| 489 | const mutation = client.defineQueued({ | |
| 490 | async mutate(_, _value: string) { | |
| 489 | const mutation = client.defineBlocking({ | |
| 490 | async mutate(_value: string) { | |
| 491 | 491 | throw new Error("mutation failed"); |
| 492 | 492 | }, |
| 493 | 493 | describe: "failing mutation", |
| ... | ... | @@ -509,8 +509,8 @@ test("QueuedMutation - multiple mutations: rollbacks only affect failed mutation |
| 509 | 509 | const { client } = createTestClient(); |
| 510 | 510 | const rollbackOrder: string[] = []; |
| 511 | 511 | |
| 512 | const mutation = client.defineQueued({ | |
| 513 | async mutate(_, id: string) { | |
| 512 | const mutation = client.defineBlocking({ | |
| 513 | async mutate(id: string) { | |
| 514 | 514 | await delay(10); |
| 515 | 515 | if (id === "fail") { |
| 516 | 516 | throw new Error("mutation failed"); |
| ... | ... | @@ -542,8 +542,8 @@ test("QueuedMutation - onRestore throws error if called after optimistic phase", |
| 542 | 542 | const { client } = createTestClient(); |
| 543 | 543 | let capturedOnRestore: ((cb: () => void) => void) | null = null; |
| 544 | 544 | |
| 545 | const mutation = client.defineQueued({ | |
| 546 | async mutate(_, _value: string) { | |
| 545 | const mutation = client.defineBlocking({ | |
| 546 | async mutate(_value: string) { | |
| 547 | 547 | return "result"; |
| 548 | 548 | }, |
| 549 | 549 | describe: "test mutation", |
| ... | ... | @@ -573,8 +573,8 @@ test("QueuedMutation - onSuccess throws error if called after optimistic phase", |
| 573 | 573 | const { client } = createTestClient(); |
| 574 | 574 | let capturedOnSuccess: ((cb: (result: string) => void) => void) | null = null; |
| 575 | 575 | |
| 576 | const mutation = client.defineQueued({ | |
| 577 | async mutate(_, _value: string) { | |
| 576 | const mutation = client.defineBlocking({ | |
| 577 | async mutate(_value: string) { | |
| 578 | 578 | return "result"; |
| 579 | 579 | }, |
| 580 | 580 | describe: "test mutation", |
| ... | ... | @@ -603,8 +603,8 @@ test("QueuedMutation - onSuccess throws error if called after optimistic phase", |
| 603 | 603 | test("QueuedMutation - error during optimistic update is rejected immediately", async () => { |
| 604 | 604 | const { client } = createTestClient(); |
| 605 | 605 | |
| 606 | const mutation = client.defineQueued({ | |
| 607 | async mutate(_, _value: string) { | |
| 606 | const mutation = client.defineBlocking({ | |
| 607 | async mutate(_value: string) { | |
| 608 | 608 | return "result"; |
| 609 | 609 | }, |
| 610 | 610 | describe: "test mutation", |
| ... | ... | @@ -625,8 +625,8 @@ test("QueuedMutation - error during optimistic update rolls back registered call |
| 625 | 625 | const { client } = createTestClient(); |
| 626 | 626 | const rollbackOrder: number[] = []; |
| 627 | 627 | |
| 628 | const mutation = client.defineQueued({ | |
| 629 | async mutate(_, _value: string) { | |
| 628 | const mutation = client.defineBlocking({ | |
| 629 | async mutate(_value: string) { | |
| 630 | 630 | return "result"; |
| 631 | 631 | }, |
| 632 | 632 | describe: "test mutation", |
| ... | ... | @@ -648,8 +648,8 @@ test("QueuedMutation - error during optimistic update rolls back registered call |
| 648 | 648 | test("QueuedMutation - refetch errors are reported but don't fail mutation", async () => { |
| 649 | 649 | const { client, errors } = createTestClient(); |
| 650 | 650 | |
| 651 | const mutation = client.defineQueued({ | |
| 652 | async mutate(_, value: string) { | |
| 651 | const mutation = client.defineBlocking({ | |
| 652 | async mutate(value: string) { | |
| 653 | 653 | return value; |
| 654 | 654 | }, |
| 655 | 655 | describe: "test mutation", |
| ... | ... | @@ -674,8 +674,8 @@ test("QueuedMutation - optimistic function receives args and helpers", async () |
| 674 | 674 | let receivedArgs: unknown[] | undefined; |
| 675 | 675 | let receivedHelpers: unknown | undefined; |
| 676 | 676 | |
| 677 | const mutation = client.defineQueued({ | |
| 678 | async mutate(_, _value: string) { | |
| 677 | const mutation = client.defineBlocking({ | |
| 678 | async mutate(_value: string) { | |
| 679 | 679 | return "result"; |
| 680 | 680 | }, |
| 681 | 681 | describe: "test mutation", |
| ... | ... | @@ -697,8 +697,8 @@ test("QueuedMutation - refetch receives context and args", async () => { |
| 697 | 697 | let receivedUserId: string | undefined; |
| 698 | 698 | let receivedArgs: unknown[] | undefined; |
| 699 | 699 | |
| 700 | const mutation = client.defineQueued({ | |
| 701 | async mutate(_, _id: string, value: string) { | |
| 700 | const mutation = client.defineBlocking({ | |
| 701 | async mutate(_id: string, value: string) { | |
| 702 | 702 | return value; |
| 703 | 703 | }, |
| 704 | 704 | describe: "test mutation", |
| ... | ... | @@ -719,8 +719,8 @@ test("QueuedMutation - notifies error on mutation failure", async () => { |
| 719 | 719 | const { client } = createTestClient(); |
| 720 | 720 | const tracker = createEventTracker<string>(); |
| 721 | 721 | |
| 722 | const mutation = client.defineQueued({ | |
| 723 | async mutate(_, _value: string) { | |
| 722 | const mutation = client.defineBlocking({ | |
| 723 | async mutate(_value: string) { | |
| 724 | 724 | await delay(10); |
| 725 | 725 | throw new Error("mutation failed"); |
| 726 | 726 | }, |
| ... | ... | @@ -747,8 +747,8 @@ test("QueuedMutation - multiple subscribers receive events", async () => { |
| 747 | 747 | const tracker1 = createEventTracker<string>(); |
| 748 | 748 | const tracker2 = createEventTracker<string>(); |
| 749 | 749 | |
| 750 | const mutation = client.defineQueued({ | |
| 751 | async mutate(_, value: string) { | |
| 750 | const mutation = client.defineBlocking({ | |
| 751 | async mutate(value: string) { | |
| 752 | 752 | await delay(5); |
| 753 | 753 | return value; |
| 754 | 754 | }, |
| ... | ... | @@ -774,8 +774,8 @@ test("QueuedMutation - onSuccess is called before mutation resolves", async () = |
| 774 | 774 | const { client } = createTestClient(); |
| 775 | 775 | const callOrder: string[] = []; |
| 776 | 776 | |
| 777 | const mutation = client.defineQueued({ | |
| 778 | async mutate(_, value: string) { | |
| 777 | const mutation = client.defineBlocking({ | |
| 778 | async mutate(value: string) { | |
| 779 | 779 | return value; |
| 780 | 780 | }, |
| 781 | 781 | describe: "test mutation", |
| ... | ... | @@ -804,8 +804,8 @@ test("QueuedMutation - result is passed to notification on success", async () => |
| 804 | 804 | const { client } = createTestClient(); |
| 805 | 805 | const tracker = createEventTracker<string>(); |
| 806 | 806 | |
| 807 | const mutation = client.defineQueued({ | |
| 808 | async mutate(_, value: string) { | |
| 807 | const mutation = client.defineBlocking({ | |
| 808 | async mutate(value: string) { | |
| 809 | 809 | await delay(5); |
| 810 | 810 | return `result-${value}`; |
| 811 | 811 | }, |
| ... | ... | @@ -834,8 +834,8 @@ test("QueuedMutation - channel is reused for same key", async () => { |
| 834 | 834 | const { client } = createTestClient(); |
| 835 | 835 | const events: string[] = []; |
| 836 | 836 | |
| 837 | const mutation = client.defineQueued({ | |
| 838 | async mutate(_, value: string) { | |
| 837 | const mutation = client.defineBlocking({ | |
| 838 | async mutate(value: string) { | |
| 839 | 839 | events.push(`mutate-${value}`); |
| 840 | 840 | return value; |
| 841 | 841 | }, |
| ... | ... | @@ -859,8 +859,8 @@ test("QueuedMutation - channel is reused for same key", async () => { |
| 859 | 859 | test("QueuedMutation - empty queue after all mutations complete", async () => { |
| 860 | 860 | const { client } = createTestClient(); |
| 861 | 861 | |
| 862 | const mutation = client.defineQueued({ | |
| 863 | async mutate(_, value: string) { | |
| 862 | const mutation = client.defineBlocking({ | |
| 863 | async mutate(value: string) { | |
| 864 | 864 | await delay(5); |
| 865 | 865 | return value; |
| 866 | 866 | }, |
| ... | ... | @@ -893,8 +893,8 @@ test("QueuedMutation - multiple onSuccess callbacks are all called", async () => |
| 893 | 893 | const { client } = createTestClient(); |
| 894 | 894 | const results: string[] = []; |
| 895 | 895 | |
| 896 | const mutation = client.defineQueued({ | |
| 897 | async mutate(_, value: string) { | |
| 896 | const mutation = client.defineBlocking({ | |
| 897 | async mutate(value: string) { | |
| 898 | 898 | return value; |
| 899 | 899 | }, |
| 900 | 900 | describe: "test mutation", |
| ... | ... | @@ -916,8 +916,8 @@ test("QueuedMutation - refetchOnSuccess false skips refetch", async () => { |
| 916 | 916 | const { client } = createTestClient(); |
| 917 | 917 | let refetchCalled = false; |
| 918 | 918 | |
| 919 | const mutation = client.defineQueued({ | |
| 920 | async mutate(_, value: string) { | |
| 919 | const mutation = client.defineBlocking({ | |
| 920 | async mutate(value: string) { | |
| 921 | 921 | return value; |
| 922 | 922 | }, |
| 923 | 923 | describe: "test mutation", |
| ... | ... | @@ -938,8 +938,8 @@ test("QueuedMutation - refetchOnSuccess false skips refetch", async () => { |
| 938 | 938 | test("QueuedMutation - refetch error after mutation failure is reported", async () => { |
| 939 | 939 | const { client, errors } = createTestClient(); |
| 940 | 940 | |
| 941 | const mutation = client.defineQueued({ | |
| 942 | async mutate(_, _value: string) { | |
| 941 | const mutation = client.defineBlocking({ | |
| 942 | async mutate(_value: string) { | |
| 943 | 943 | throw new Error("mutation failed"); |
| 944 | 944 | }, |
| 945 | 945 | describe: "failing mutation", |