Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/reactive/async-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,12 @@ export const useFetch = <TResponse = unknown, TData = TResponse>(
const retryConfig = normalizeRetryConfig(options.retry);
const maxAttempts = (retryConfig?.count ?? 0) + 1;

// Abort controller: compose timeout + external signal + manual abort
// Abort controller: compose timeout + external signal + manual abort.
// Abort any still-in-flight controller from a superseded execution first —
// overlapping executes (e.g. a watch refresh racing a manual refresh())
// would otherwise leave the earlier fetch running, un-cancellable, until it
// resolves (only its result is discarded by the executionId guard).
currentAbortController?.abort();
const abortController = new AbortController();
currentAbortController = abortController;
let timeoutId: ReturnType<typeof setTimeout> | undefined;
Expand Down
36 changes: 36 additions & 0 deletions tests/signal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1223,6 +1223,42 @@ describe('useFetch', () => {
expect(requests).toHaveLength(1);
});

it('aborts a superseded in-flight request when a new execution starts (#172)', async () => {
const signals: AbortSignal[] = [];
let releaseFirst: (() => void) | undefined;

const state = useFetch<{ ok: boolean }>('/api/slow', {
immediate: false,
fetcher: asMockFetch((_input, init) => {
const signal = init?.signal as AbortSignal | undefined;
if (signal) signals.push(signal);
return new Promise<Response>((resolve, reject) => {
if (signal) {
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
}
// The first request hangs until released; the second resolves.
if (!releaseFirst) {
releaseFirst = () => resolve(new Response(JSON.stringify({ ok: true }), { status: 200 }));
} else {
resolve(new Response(JSON.stringify({ ok: true }), { status: 200 }));
}
});
}),
});

// Start two overlapping executions; the second must abort the first.
const first = state.execute().catch(() => undefined);
const second = state.execute();

await second;
expect(signals).toHaveLength(2);
expect(signals[0].aborted).toBe(true);
expect(signals[1].aborted).toBe(false);

releaseFirst?.();
await first;
});

it('serializes plain object bodies as JSON', async () => {
let body = '';
let contentType = '';
Expand Down