Skip to content

Commit

Permalink
fix: don't reuse promise after cancel
Browse files Browse the repository at this point in the history
  • Loading branch information
Coronon committed Nov 2, 2024
1 parent 7578f21 commit 6d15216
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ export function useDebounce<Args extends unknown[], Return>(
}

clearTimeout(context.timeout);
context.timeout = undefined;
context.reject("Cancelled");
context = null;
};

Object.defineProperty(debounced, "pending", {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,29 @@ describe("useDebounce", () => {
expect(fn).not.toHaveBeenCalled();
});

testWithEffect("Doesn't reuse promise after cancel", async () => {
// Same as above
const fn = vi.fn();
const debounced = useDebounce(fn, 100);

expect(fn).not.toHaveBeenCalled();
debounced().catch(() => {});
expect(fn).not.toHaveBeenCalled();
expect(debounced.pending).toBe(true);
debounced.cancel();
expect(debounced.pending).toBe(false);
await new Promise((resolve) => setTimeout(resolve, 200));
expect(fn).not.toHaveBeenCalled();

// New test
let wasCatchCalled = false;
debounced().catch(() => (wasCatchCalled = true));
expect(wasCatchCalled).toBe(false);
await new Promise((resolve) => setTimeout(resolve, 110));
expect(wasCatchCalled).toBe(false);
expect(fn).toHaveBeenCalledTimes(1);
});

testWithEffect("No race contion with running callback", async () => {
let calledNTimes = 0;

Expand Down

0 comments on commit 6d15216

Please sign in to comment.