Skip to content

Lesson 5 of 9 · 25m

Server Data in Vue: Loading, Races, and Cache Boundaries

Fetch patterns that handle cancellation, stale responses, pagination, and mutations without turning components into networking spaghetti.

Vue does not prescribe a server-state layer, which is both freedom and trap. A raw fetch in onMounted is fine for a settings page with one request. It collapses once users type quickly, paginate, retry mutations, or revisit cached screens. Production Vue needs the same discipline as any other frontend: identify ownership, races, cache lifetime, and mutation behavior.

The race is the first bug

watch(
  () => route.params.id,
  async (id) => {
    const user = await fetchUser(String(id));
    state.user = user; // wrong if the user navigated before this resolved
  },
  { immediate: true },
);

Use an AbortController or a request-generation guard:

watch(
  () => route.params.id,
  async (id) => {
    const controller = new AbortController();
    controllers.get("user")?.abort();
    controllers.set("user", controller);

    try {
      state.user = await fetchUser(String(id), { signal: controller.signal });
      state.error = null;
    } catch (error) {
      if (!isAbortError(error)) state.error = error;
    }
  },
  { immediate: true },
);

The point is not the exact helper — it is acknowledging that async responses arrive after the state that requested them may have changed.

Model request status explicitly

type RequestState<T> =
  | { status: "idle" }
  | { status: "pending" }
  | { status: "success"; data: T }
  | { status: "error"; error: Error };

Booleans like loading and loaded create impossible combinations and forget the empty-success case. Users need four designed states: loading, error, empty, success. A search returning zero rows is not an exception, and a spinner that never resolves is usually an untested error branch.

Mutations need identity, not hope

async function saveInvoice(invoice: InvoiceDraft) {
  const optimistic = applyOptimisticUpdate(invoice);
  try {
    const saved = await api.invoices.save(invoice);
    replaceInvoice(saved);
  } catch (error) {
    rollback(optimistic);
    notifyError("Invoice could not be saved");
  }
}

Optimistic updates are valuable when the user expects instant feedback — toggles, reordering, starring. Capture rollback state before mutation and reconcile with the server response afterward. Do not pretend failure is impossible; networks and permission checks exist.

Cache at the right layer

Browser cache, HTTP cache, route-level reuse, and app-level query caches solve different problems. VueUse useFetch is convenient for simple calls; TanStack Query's Vue adapter or a custom resource layer is justified when deduplication, invalidation, retries, and window-refetch behavior matter. Pick the layer consciously rather than growing accidental caching inside each component.

Field notes

  • Abort stale requests on input-driven queries; otherwise the slowest response can overwrite the newest intent.
  • Paginated APIs need cursor identity, not just page numbers, if the underlying data can change while the user scrolls.
  • Keep serialization boundaries narrow: parse dates and validate API payloads at the edge, not throughout the UI.
  • Retrying idempotent GETs is safe; blindly retrying POSTs can duplicate writes unless the backend supports idempotency keys.

Was this lesson helpful?

Sign in to rate