diff --git a/readme.changes.md b/readme.changes.md index 77081b7aa1a5e76ab4266a390da9d07ca03d9af0..dd6053b89e6c4f1ea80f67f2ffe09a65399ca6c7 100644 --- a/readme.changes.md +++ b/readme.changes.md @@ -12,6 +12,8 @@ - resolve `runWithOptions` (and so `MutationButton`) setting `isPending` and disabling controls for debounced mutations, and leaving a pending delay from an earlier `run` to set `isPending` later +- resolve a debounced call made during an in-flight request running alongside + it, which let the first request mark the mutation idle mid-flight ## v3.0.2 diff --git a/src/mutation.ts b/src/mutation.ts index 16d06bd3af23e65b6baf14e09ed35f7e88dfae85..7b6cd23dc13efd4f6b487678f40abd01b13651ee 100644 --- a/src/mutation.ts +++ b/src/mutation.ts @@ -817,9 +817,11 @@ export class BlockingMutation< shouldCallGlobalHandler, }; - // Set status to waiting - channel.status = "waiting"; - this.#notify(channel, "waiting"); + // An in-flight request picks the call up when it finishes + if (channel.status === "idle") { + channel.status = "waiting"; + this.#notify(channel, "waiting"); + } } else { // Subsequent debounced call - update state channel.pendingDebounced.args = args; diff --git a/test/ordering.test.ts b/test/ordering.test.ts index dac4168bdf5f367c2fa52c46372f7abc47ff243a..e5e7f2d9f3077b15656904c7026af49277b43426 100644 --- a/test/ordering.test.ts +++ b/test/ordering.test.ts @@ -491,3 +491,34 @@ test("a synchronous throw from mutate fails the call without wedging the channel assertEquals(errorMessages.map((e) => e.message), ["Could not test: Sync failure"]); assertEquals(successMessages, ["Completed 2"]); }); + +test("a debounced call made during an in-flight request waits for it", async () => { + vi.useFakeTimers(); + const { client } = createTestMutationClient(); + const calls: string[] = []; + + const mutTest = client.define({ + id: "test-12", + mutate: async (id: number) => { + calls.push(`start-${id}`); + await delay(100); + calls.push(`end-${id}`); + return `result-${id}`; + }, + describe: "test", + describeResult: null, + optimistic: () => {}, + refetchOnSuccess: false, + debounceMs: 10, + }); + mutTest.subscribe(mutTest.key([1]), ({ status }) => { + if (status === "idle") calls.push("idle"); + }); + + mutTest.run(1); + await vi.advanceTimersByTimeAsync(50); + mutTest.run(2); + await vi.advanceTimersByTimeAsync(500); + + assertEquals(calls, ["start-1", "end-1", "start-2", "end-2", "idle"]); +});