javascript / expert
Snippet
Async Race Condition Prevention with AbortController
In Svelte's reactive effects, subsequent updates can trigger new fetch requests before previous ones finish. By using AbortController in the effect's cleanup function, we ensure that stale requests are cancelled, preventing UI inconsistencies and memory leaks.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$effect(() => {const controller = new AbortController();const signal = controller.signal;async function loadData() {try {const response = await fetch(`/api/data/${id}`, { signal });data = await response.json();} catch (err) {if (err.name !== 'AbortError') console.error(err);}}loadData();return () => controller.abort();});
svelte
Breakdown
1
const controller = new AbortController();
Initializes a new controller to manage the cancellation signal for the current effect execution.
2
return () => controller.abort();
The cleanup function called by Svelte before the effect re-runs or the component is destroyed, triggering the cancellation.