authoravatarclover caruso<git@paperclover.net>2026-10-14 17:57:46-07:00
committeravatarclover caruso<git@paperclover.net>2026-11-11 11:13:55-08:00
log753ee8624109c92d55060573e22caa23be8d6ce9
tree8d153e3db4c3d4e38049d89aab49df2fde2e70b4
parent002a02c932f1c7bde73e75b4177b2a6f50e3956d
signature Signed by SSH key SHA256:cOKiuRFOeSRxne6EWgHtdQQSlBxjOXm2hOCFnCdLQbQ

fix: respect debounce and clear stale delays in runWithOptions

The runWithOptions subscription never recorded `debounced` and set isPending for debounced mutations, so a debounced mutation behind a MutationButton showed as pending and disabled the button while its request ran, contrary to the documented behaviour. Switching keys from a run() subscription also left that subscription's pendingTimer alive to set isPending after the new key went idle. Assisted-by: claude-opus-5.5 Assisted-by: claude-opus-5

4 files changed, 85 insertions(+), 3 deletions(-)

readme.changes.md+3
......@@ -9,6 +9,9 @@
99 the mutation stuck in its mutating state
1010- resolve `useMutate` setting `isPending` after its mutation is swapped within
1111 the 200ms pending delay
12- resolve `runWithOptions` (and so `MutationButton`) setting `isPending` and
13 disabling controls for debounced mutations, and leaving a pending delay from
14 an earlier `run` to set `isPending` later
1215
1316## v3.0.2
1417
src/react.ts+5-2
......@@ -350,9 +350,12 @@ class Observer<Args extends unknown[], Result> {
350350 if (key !== this.currentKey) {
351351 this.currentKey = key;
352352 this.unsubscribe?.();
353 this.resetPending();
353354 this.unsubscribe = mutation.subscribe(
354355 mutation.key(args),
355 ({ status, error, result }) => {
356 ({ status, error, result, debounced }) => {
357 this.debounced = debounced;
358
356359 if (status === "idle") {
357360 this.setState({
358361 isMutating: false,
......@@ -378,7 +381,7 @@ class Observer<Args extends unknown[], Result> {
378381 : this.computeErrorMessage(error ?? undefined),
379382 result: result ?? undefined,
380383 isMutating: status === "mutating",
381 isPending: status === "mutating" || status === "refetching",
384 isPending: !debounced && (status === "mutating" || status === "refetching"),
382385 isSuccess: hasResult && !hasError,
383386 isError: hasError,
384387 isOptimisticData: status === "waiting" || status === "mutating"
test/debounce.test.tsx+42-1
......@@ -1,7 +1,8 @@
1import { useMutate } from "@clo/react-mutation";
1import { createMutationButton, useMutate } from "@clo/react-mutation";
22import { assertEquals } from "@std/assert";
33import { act, render, screen } from "@testing-library/react";
44import { userEvent } from "@testing-library/user-event";
5import type { FC, MouseEventHandler, ReactNode } from "react";
56import { test, vi } from "vitest";
67import { createTestMutationClient, IterableStream } from "./share.ts";
78
......@@ -181,6 +182,46 @@ test("debounceMs: batch multiple calls together", async () => {
181182 renders = [];
182183});
183184
185test("debounceMs: a mutation button stays enabled and not pending while mutating", async () => {
186 vi.useFakeTimers({ shouldAdvanceTime: true });
187 const user = userEvent.setup({ delay: null });
188
189 const { client } = createTestMutationClient();
190 const s = new IterableStream<string>();
191
192 const mutTest = client.define({
193 id: "test-button",
194 mutate: async () => {
195 return (await s.next()).value;
196 },
197 describe: "Test the action",
198 describeResult: null,
199 optimistic: () => {},
200 debounceMs: 500,
201 });
202
203 let last = {};
204 const MutationButtonBase: FC<{
205 children?: ReactNode;
206 disabled?: boolean;
207 isPending: boolean;
208 onClick: MouseEventHandler<HTMLElement> | undefined;
209 }> = function MutationButtonBase({ children, disabled, isPending, onClick }) {
210 last = { disabled, isPending };
211 return (
212 <button data-testid="a" onClick={onClick}>
213 {children}
214 </button>
215 );
216 };
217 const MutationButton = createMutationButton(MutationButtonBase);
218
219 render(<MutationButton mutation={mutTest} args={[]}>button</MutationButton>);
220 await act(() => user.click(screen.getByTestId("a")));
221 await act(() => vi.advanceTimersByTime(1000));
222 assertEquals(last, { disabled: false, isPending: false });
223});
224
184225test.todo("debounceImmediate runs the first one right away", async () => {
185226 vi.useFakeTimers({ shouldAdvanceTime: true });
186227 const user = userEvent.setup({ delay: null });
test/useMutate.test.tsx+35
......@@ -173,6 +173,41 @@ test("useMutate - swapping the mutation within the pending delay never sets isPe
173173 assertEquals(isPending, false);
174174});
175175
176test("useMutate - runWithOptions on another key clears the pending delay from run", async () => {
177 vi.useFakeTimers({ shouldAdvanceTime: true });
178 const user = userEvent.setup({ delay: null });
179
180 const { client } = createTestMutationClient();
181
182 const mutTest = client.define({
183 id: "test-pending-handoff",
184 mutate: (id: number) => id === 1 ? new Promise<string>(() => {}) : Promise.resolve("ok"),
185 key: ({ args: [id] }) => String(id),
186 describe: "Test the action",
187 describeResult: null,
188 optimistic: () => {},
189 refetchOnSuccess: false,
190 });
191
192 let isPending = false;
193 function TestComponent() {
194 const state = useMutate(mutTest);
195 isPending = state.isPending;
196 return (
197 <>
198 <button data-testid="a" onClick={() => state.run(1)}>a</button>
199 <button data-testid="b" onClick={() => state.runWithOptions(2, {})}>b</button>
200 </>
201 );
202 }
203
204 render(<TestComponent />);
205 await act(() => user.click(screen.getByTestId("a")));
206 await act(() => user.click(screen.getByTestId("b")));
207 await act(() => vi.advanceTimersByTime(500));
208 assertEquals(isPending, false);
209});
210
176211test("useMutate - local error and success handling", async () => {
177212 vi.useFakeTimers({ shouldAdvanceTime: true });
178213 const user = userEvent.setup({ delay: null });