Composition API or Options API?
Related reading: React Hooks: useState, useEffect and More.
Both use Vue's reactivity system. Options API groups code by option type, while Composition API can group it by feature. Working components need not be migrated merely for style. In single-file components, <script setup> compiles to setup logic executed per instance rather than on every render like a React function component body. [1][2]
ref, reactive and computed
reactivity.ts
import { computed, reactive, ref, toRefs } from "vue";
export function useQuantity() {
const quantity = ref(1);
const pricing = reactive({ unitPrice: 2500 });
const { unitPrice } = toRefs(pricing);
const total = computed(() => quantity.value * unitPrice.value);
return { quantity, unitPrice, total };
}
ref exposes its value through .value in TypeScript; templates unwrap top-level refs. reactive creates an object proxy. Destructuring an ordinary numeric or string property disconnects it from tracking; toRefs preserves the connection. computed caches a calculation based on reactive dependencies. Do not make requests or mutate state inside its getter. The example calculates a price in minor currency units, not a complete money model. [3][4]
watch, watchEffect and scheduling
watch declares a source and is lazy by default; immediate changes its initial execution. watchEffect runs immediately and tracks reads during synchronous execution, not after the first await. Default watchers are batched and run before their owner's DOM update; flush: "post" enables reads of updated DOM. nextTick() waits for Vue's update flush, not necessarily browser paint. flush: "sync" bypasses batching, so the example limits it to a single text value to invalidate old searches immediately. [3][5]
HTTP contract and runtime validation
Related reading: TypeScript Type Guards: Narrowing and Runtime Validation.
products.ts
export interface Product {
readonly id: string;
readonly name: string;
}
function isRecord(value: unknown): value is Record<string, unknown> {
if (value === null) {
return false;
}
if (Array.isArray(value)) {
return false;
}
return typeof value === "object";
}
function isNonBlankString(value: unknown): value is string {
if (typeof value !== "string") {
return false;
}
return value.trim().length > 0;
}
export function parseProducts(value: unknown): readonly Product[] {
if (!Array.isArray(value)) {
throw new TypeError("Expected a product array.");
}
const entries: unknown[] = value;
const ids = new Set<string>();
const products: Product[] = [];
for (const item of entries) {
if (!isRecord(item)) {
throw new TypeError("Expected a product object.");
}
const { id, name } = item;
if (!isNonBlankString(id)) {
throw new TypeError("Invalid product ID.");
}
if (!isNonBlankString(name)) {
throw new TypeError("Invalid product name.");
}
if (ids.has(id)) {
throw new TypeError("Duplicate product ID.");
}
ids.add(id);
products.push({ id, name });
}
return products;
}
products-api.ts
import { parseProducts } from "./products";
import type { Product } from "./products";
export type ProductLoader = (
query: string,
signal: AbortSignal,
) => Promise<readonly Product[]>;
const REQUEST_TIMEOUT_MS = 10_000;
export function createProductLoader(
endpoint: URL,
transport: typeof fetch = fetch,
): ProductLoader {
return async (query, signal) => {
const url = new URL(endpoint);
url.searchParams.set("q", query);
const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
const requestSignal = AbortSignal.any([signal, timeout]);
const response = await transport(url, {
signal: requestSignal,
headers: { Accept: "application/json" },
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data: unknown = await response.json();
return parseProducts(data);
};
}
A TypeScript generic does not validate a server response at runtime. The adapter receives a URL and transport, encodes the query via URLSearchParams, combines cancellation with a deadline and checks HTTP status before reading JSON. The parser rejects malformed records, blank names and duplicate identifiers because IDs serve as list keys. Guard clauses separate structural checks from value checks. A production backend must independently enforce authorization and request limits. [6][7] [13][16]
Composable: state and cancellation
use-product-search.ts
import { computed, ref, shallowRef, watch } from "vue";
import type { ProductLoader } from "./products-api";
import type { Product } from "./products";
type SearchState =
| { readonly status: "idle" }
| { readonly status: "loading" }
| { readonly status: "success"; readonly items: readonly Product[] }
| { readonly status: "error" };
export const SEARCH_DELAY_MS = 300;
export function useProductSearch(load: ProductLoader) {
const query = ref("");
const normalizedQuery = computed(() => query.value.trim());
const state = shallowRef<SearchState>({ status: "idle" });
watch(
normalizedQuery,
(term, _previousTerm, onCleanup) => {
if (term.length === 0) {
state.value = { status: "idle" };
return;
}
const controller = new AbortController();
async function execute(): Promise<void> {
try {
const items = await load(term, controller.signal);
if (controller.signal.aborted) {
return;
}
state.value = { status: "success", items };
} catch {
if (controller.signal.aborted) {
return;
}
state.value = { status: "error" };
}
}
const timer = setTimeout(() => {
void execute();
}, SEARCH_DELAY_MS);
onCleanup(() => {
clearTimeout(timer);
controller.abort();
});
state.value = { status: "loading" };
},
{ flush: "sync" },
);
return { query, state: computed(() => state.value) };
}
useProductSearch accepts a data loader and returns a query ref plus a read-only computed state ref. A discriminated union prevents treating an error as success. Each normalized query change clears the previous timer and aborts the request through watcher cleanup. Checking the signal after await also protects against loaders that ignore cancellation. shallowRef is deliberate: replace the state instead of mutating nested results. The 300 ms delay is an illustrative UX decision, not a universal rule. [5][8][9]
Component, props and lifecycle
ProductSearch.vue
<script setup lang="ts">
import { useId } from "vue";
import type { ProductLoader } from "./products-api";
import { useProductSearch } from "./use-product-search";
const props = defineProps<{ load: ProductLoader }>();
const searchId = useId();
const { query, state } = useProductSearch((term, signal) =>
props.load(term, signal),
);
</script>
<template>
<section class="product-search">
<label :for="searchId">Search products</label>
<input :id="searchId" v-model="query" type="search" />
<p role="status">
<template v-if="state.status === 'loading'">Searching…</template>
<template v-else-if="state.status === 'success'">
{{ state.items.length }} results
</template>
<template v-else-if="state.status === 'error'">
Search failed. Change the query to try again.
</template>
</p>
<ul v-if="state.status === 'success'">
<li v-for="item in state.items" :key="item.id">
{{ item.name }}
</li>
</ul>
</section>
</template>
<style scoped src="./product-search.css"></style>
product-search.css
.product-search {
display: grid;
gap: 0.75rem;
max-inline-size: 36rem;
}
.product-search input {
font: inherit;
padding: 0.625rem;
}
The SFC uses v-model, a label associated with the input via useId, and a status message. Vue directives are framework-compiled declarative bindings, not native onclick attributes. Since Vue 3.5, destructured props in the same <script setup> can remain reactive through compilation; pass a getter or ref to external functions instead of a value snapshot. Watchers created synchronously in setup stop on unmount. The 3.5+ onWatcherCleanup must be called synchronously; the example uses the onCleanup argument registered before the request starts. [2][5][10] [14][16]
SSR, shared state and performance
App.vue
<script setup lang="ts">
import ProductSearch from "./ProductSearch.vue";
import { createProductLoader } from "./products-api";
const endpoint = new URL("/api/products", window.location.origin);
const load = createProductLoader(endpoint);
</script>
<template>
<main>
<h1>Product catalog</h1>
<ProductSearch :load="load" />
</main>
</template>
Keep component state local, share logic through composables, and adopt a store for state shared by views when needed. With SSR, do not keep user-specific data in a module singleton; isolate state per request. Access window or document only on the client, for instance after onMounted. The supplied App.vue is CSR-only; in Nuxt or another SSR environment inject an appropriate transport and use its data-fetching facilities. Avoid deep watchers over large structures without measuring their cost. [8][9][11] [15]
Testing and acceptance criteria
use-product-search.test.ts
import { effectScope } from "vue";
import { afterEach, expect, it, vi } from "vitest";
import type { Product } from "./products";
import { SEARCH_DELAY_MS, useProductSearch } from "./use-product-search";
afterEach(() => {
vi.useRealTimers();
});
it("ignores outdated responses from non-cooperative loaders", async () => {
// Given
vi.useFakeTimers();
const scope = effectScope();
const oldItems: readonly Product[] = [{ id: "1", name: "Old" }];
const newItems: readonly Product[] = [{ id: "2", name: "New" }];
let finishOld: (items: readonly Product[]) => void = () => {};
const oldResponse = new Promise<readonly Product[]>((resolve) => {
finishOld = resolve;
});
const search = scope.run(() =>
useProductSearch(async (query) => {
if (query === "old") {
return oldResponse;
}
return newItems;
}),
);
try {
if (!search) {
throw new Error("Missing active scope.");
}
// When
search.query.value = "old";
await vi.advanceTimersByTimeAsync(SEARCH_DELAY_MS);
search.query.value = "new";
await vi.advanceTimersByTimeAsync(SEARCH_DELAY_MS);
finishOld(oldItems);
await vi.advanceTimersByTimeAsync(0);
// Then
expect(search.state.value).toEqual({
status: "success",
items: newItems,
});
} finally {
scope.stop();
}
});
it("cancels scheduled work when its scope stops", async () => {
// Given
vi.useFakeTimers();
const scope = effectScope();
const load = vi.fn(async () => []);
const search = scope.run(() => useProductSearch(load));
try {
if (!search) {
throw new Error("Missing active scope.");
}
// When
search.query.value = "book";
scope.stop();
await vi.advanceTimersByTimeAsync(SEARCH_DELAY_MS);
// Then
expect(load).not.toHaveBeenCalled();
} finally {
scope.stop();
}
});
Test the pure parser and adapter without Vue. Test the composable inside an effectScope with controlled timers and an injected loader. Given-When-Then describes initial conditions, action and outcome without requiring Cucumber. Cover empty queries, server errors, malformed JSON, rapid changes, out-of-order responses and disposal. Separately verify the actual component, focus and accessible announcements. The package includes two Vitest tests and independent Node checks; neither substitutes for end-to-end tests. [12]
