javascript / expert
Snippet
Handling Race Conditions in watchEffect
When performing asynchronous operations inside a watcher, a race condition occurs if a new effect starts before the previous one finishes. Using the onCleanup callback allows you to invalidate previous pending requests or local state variables.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
import { watchEffect, ref } from 'vue';const id = ref(1);watchEffect(async (onCleanup) => {let active = true;onCleanup(() => active = false);const data = await fetch(`https://api.example.com/item/${id.value}`);if (active) {console.log('Update UI with:', data);}});
vue
Breakdown
1
watchEffect(async (onCleanup) => { ... });
Accepts an onCleanup callback that runs whenever the effect re-triggers.
2
onCleanup(() => active = false);
Registers a cleanup function to flag the current execution as stale.
3
if (active) { ... }
Ensures that the UI is only updated if this specific async call is still relevant.