---
description: "Components only declare which slice of data they need; fetching, cancelling, merging and error feedback belong to the host. This page generalizes the table's windowed / infinite / server row-model protocols into a standard posture for any component talking to a server, with cache helpers and per-component lazy-loading points."
---

# Data Fetching Recipes

The library does not fetch data (just as it does not do routing) — **components only declare which slice of data they need; fetching, cancelling, merging and error feedback belong to the host**. But *how* to declare it is standardized: three protocols cover paged browsing, scroll-to-append and hundred-thousand-row windows, and the `@oas-ui/ui/data/table/advanced` helpers pack protocol listening, race guards, caching and failure reporting into host-side glue. This page describes the general posture; [Server-side windowed data](/en/guide/windowed-data) is the complete recipe for the windowed protocol with a runnable example.

## The three host fetching protocols

All three share one boundary: **the component computes which slice it needs and emits a request event; the host fetches by the event detail and refills attributes / calls a refill method**. The component does not own the full dataset (except in client form), and never issues HTTP requests for the host.

### windowed: slice windows

For hundred-thousand-row datasets that must be scrolled (table / gantt / resource / tree / list).

- **Component side**: `windowed` to enable + `total` (full row count) + `window-start` (absolute row index of `data[0]`); `data` carries only the slice `[window-start, window-start + data.length)`.
- **Request**: `oas-window-request` with `detail: { start, end, reason, visualStart?, visualEnd? }` (half-open, absolute indices; `reason` = `init` / `scroll` / `resize` / `data`). The same expected window is never emitted twice; it resets once covered.
- **Refill**: write `data` first, then `window-start` (same synchronous step) to avoid a "new slice + old start" intermediate state; merge edit write-backs by id — **never replace the full dataset**.
- **Built in**: same-window request dedupe, loaded-coverage check, and dispatching inside the scroll frame before the tbody rebuild (so the authoritative scroll position is not mis-clamped during the clear).
- **Host must**: fetch by segments (not per window) to cut request count; keep only the latest request; respect the fetcher `signal`.

### infinite: cursor scroll-to-append

For feeds / logs / search results — long lists with no page number where scrolling to the bottom loads more.

- **Component side**: `infinite` to enable; `total` optional (an unknown total is ended by the host's empty-block signal); `max-loaded-rows` optional (buffer cap; the oldest rows are evicted past the cap, and the cursor chain plus the end signal are unaffected).
- **Request**: `oas-rows-request` with `reason` = `load-more` and `detail.cursor` echoing the cursor recorded by the last `appendRows` (absent on the first request); sort / filter changes reset the buffer and request the first block again.
- **Refill**: `appendRows(rows, { cursor?, total?, requestId? })`; **an empty array means no more data** (stop triggering and show the "reached the end" row). Do not append through the `data` attribute — writing `data` resets the loaded buffer.
- **Failure**: `reportRowsError({ requestId, reason?, error? })` feeds the built-in error bar + `oas-rows-error` + retry button.
- **Built in**: monotonic `requestId`; `appendRows` sequence guard (late responses dropped silently, same-id refills idempotent); eviction does not renumber rows; end-of-data signal.
- **Host must**: pass the request detail's `requestId` back to `appendRows` / `reportRowsError`; implement fetcher timeouts.

### server row model: paging, sorting, filtering, aggregation

For enterprise datasets: sorting / filtering / paging / grouping / aggregation all happen on the server, and `data` carries only the current page slice.

- **Component side**: `row-model="server"` + `total` (prerequisite; write the total back with each response) + `pagination` (optional); `group-by` together switches to the server grouping protocol (the host returns mixed rows with `kind: 'group'`).
- **Request**: `oas-rows-request` with `detail: { requestId, start, end, sortModel, filterValues, reason, totalKnown, groupBy? }`; `reason` = `init` / `paginate` / `sort` / `filter` / `group` / `refresh`. Sort / filter / page-size / group-key changes reset `current` to 1 before requesting.
- **Refill**: write `data` and `total`; on failure use `reportRowsError` to settle loading and show the error bar. **Do not write other attributes synchronously in the same listener** (that re-enters rendering); the refill itself is just attribute writes.
- **Built in**: `requestId` sequence guard; built-in loading rows while in flight; failures keep old data + error bar + `oas-rows-error`.
- **Host must**: actually perform sorting / filtering / grouping on the server (the component skips local transforms entirely); align the page slice with `start` / `end`.

### Responsibility cheat sheet

| Dimension | Component | Host |
| --- | --- | --- |
| Range computation | window / cursor / page → request detail | fetch by detail (HTTP / RPC) |
| Dedupe & races | monotonic requestId, same-window dedupe, sequence guards | cancel in-flight, drop late responses (most already in the helpers) |
| Loading & merging | slice rendering, absolute row indices, eviction without renumbering | merge edit write-backs by id, never replace wholesale |
| Feedback | loading rows / error bar / retry (server, infinite) | timeouts, retry policy, business error copy |
| Data ownership | only the loaded slice | full dataset and cache policy |

## The createServerSource / createWindowedSource cache pattern

Both helpers live in `@oas-ui/ui/data/table/advanced` (host-side-only modules; they add no component API and change no component behavior). Shared prerequisites: **the element is upgraded and connected** (append first, then create); **one source instance per element** (creating a second one doubles listeners and fetches and warns once; call `destroy()` first and rebuild).

### Glue for the server row model

```ts
import { createServerSource } from '@oas-ui/ui/data/table/advanced'

const source = createServerSource(table, {
  total: 1000, // optional: write total before mounting (server prerequisite)
  fetchRows: async ({ requestId, start, end, sortModel, filterValues, groupBy, signal }) => {
    // requestId can be forwarded to the server for trace correlation; signal aborts the previous fetch on paging / destroy
    const res = await api.listOrders({ start, end, sort: sortModel, filter: filterValues, groupBy, signal })
    return { rows: res.list, total: res.total } // returning total syncs the total attribute automatically
  },
})
// source.refresh(): force-refresh the current page (reason='refresh', bypassing value dedupe)
// source.refresh({ purge: true }): clear the whole cache, then refetch
// source.destroy(): unbind listeners + abort in-flight + clear cache bookkeeping
```

The built-in cache is enabled by default: the key is the full query signature (range / sort / filter / group / cursor, independent of `reason`), TTL defaults to 5 minutes, the entry cap is 200 (LRU), and identical in-flight requests are merged. `cache: false` disables it; `{ ttlMs, maxEntries, staleWhileRevalidate }` configures it — with SWR, an expired hit refills stale data first and revalidates in the background. **This helper only serves "server paging / grouping"; do not combine it with `infinite`** (whole-page `data` overwrite conflicts with `appendRows` append semantics). For infinite, manage `oas-rows-request` on the host yourself.

Timeouts and cancellation are a data-layer concern: the component has no built-in request timeout. Combine the helper's `signal` with a timeout signal inside `fetchRows`:

```ts
fetchRows: async ({ signal, ...rest }) => {
  const res = await api.listOrders({ ...rest, signal: AbortSignal.any([signal, AbortSignal.timeout(8000)]) })
  return { rows: res.list, total: res.total }
}
```

### Glue for windowed

```ts
import { createWindowedSource } from '@oas-ui/ui/data/table/advanced'

const source = createWindowedSource(table, {
  windowSize: 50, // first-screen window size (default 50; should not exceed the server's per-request limit)
  total: 50000, // optional; synced automatically when fetchRows returns total
  fetchRows: async ({ start, end, signal }) => {
    const rows = await api.listRows({ start, end, signal })
    return rows // returning { rows, total } also works
  },
})
// source.refresh(): refetch the most recent window (first screen if none recorded); source.destroy(): unbind + abort in-flight
```

The helper listens to `oas-window-request`, aborts the previous in-flight fetch, records loaded coverage by the actual returned row count, and atomically refills `data` / `window-start` / `total`. An optional `visual` adapter (`getGeometry` / `getDataRange`) supports the visual protocol where rows before the slice start are already expanded; see [Server-side windowed data](/en/guide/windowed-data#visual-protocol-recipe-inline-expand-rows-slices-starting-after-expanded-rows) and the table page.

> Both helpers are **host-side protocol glue only**: they do not change the component contract, nor decide the cache backend for the host. To plug in IndexedDB or a server cache, replace `fetchRows`.

## Lazy-loading points in other components

The table is not the only component that can talk to a server. Each component has its own fetch trigger and refill channel, but all follow "event notification + attribute refill":

| Component | Fetch trigger | Host refill | Failure / races |
| --- | --- | --- | --- |
| `oas-table` (windowed) | `oas-window-request` | write `data` + `window-start` (data first, then start) | `createWindowedSource` has abort + coverage checks |
| `oas-table` (infinite) | `oas-rows-request` (`reason=load-more`) | `appendRows(rows, { cursor, total, requestId })` | requestId guard; empty array = end; `reportRowsError` |
| `oas-table` (server) | `oas-rows-request` (`init` / `paginate` / `sort` / `filter` / `group` / `refresh`) | write `data` + `total` | requestId guard; `reportRowsError` drives the built-in error bar |
| `oas-combobox` | user input `oas-input` (and `oas-open-change` on open) | write `options` property / attribute, set `loading` while pending | no built-in request protocol: host debounces, drops by sequence, clears `loading` |
| `oas-auto-complete` | `oas-input` (built-in `debounce`, default 0) | write `options`, set `loading` while pending | same as above; the natural fit for "type-ahead remote suggestions" |
| `oas-tree` | `oas-load` (`detail: { key }`, expanding an unloaded node under `lazy`) | refill children then reset `data`; write `children: []` for a loaded-empty node | `load` rejection → `oas-load-error` (`detail: { key, error }`) + retry |
| `oas-cascader` | `el.load = ({ option, path, depth }) => Promise<options>` (expanding an unloaded node) | the `load` return value supplies child options; a node may carry `isLeaf` | during `loading` the panel shows only the loading placeholder; handle failure inside `load` |

Two general rules:

- **Input components have no "request event"**: combobox / auto-complete only report user input (`oas-input`); remote matching / sorting / dedupe are entirely the host's job. `loading` is how the host tells the component a request is in flight.
- **Tree / cascader own their loading state**: `oas-load` fires once when an unloaded node is expanded; after refilling, the host must reset `data` (or return children), otherwise the component stays on the loading placeholder.

## Choosing a protocol

Choose by "data size × interaction shape"; never mix per-segment ("sort only the current page" is wrong semantics and is not configurable):

| Shape | Fits | Component | Host |
| --- | --- | --- | --- |
| client (full `data`) | up to tens of thousands of rows; sorting / filtering / paging on the client | all transforms, page slicing, rendering | provide the data once |
| `row-model="server"` | enterprise datasets; sorting / filtering / grouping on the server | request protocol, loading / error bar, requestId guard; `createServerSource` adds caching | run the query; return the current page / group rows per detail |
| `infinite` | feeds / logs / result streams; no paging | cursor chain, scroll-to-bottom, buffer cap, end signal | return the next block per cursor; refill via `appendRows` |
| windowed | hundred-thousand-row scrolling; feed only the visible slice | window computation, spacer rows, dedupe | segmented fetching, merging, atomic refill; optional `createWindowedSource` |
| host-managed event listeners | deep customization (SSE, custom cache / merge) | only emit request events | own fetching, cancellation and errors completely |

Mutual-exclusion priority (when enabled together): `windowed` > `row-model="server"`; `windowed` > `infinite`; `pagination` > `infinite`; `infinite` > `row-model="server"`. Each warns once via `devWarn`; pick one per scenario.

## Race-guard division of labor

**Already handled by the component** (do not duplicate):

- Monotonic `requestId`; `reportRowsError` only takes effect while the id is still the latest.
- `appendRows` requestId guard: late responses are dropped, same-id refills are idempotently ignored.
- windowed never emits the same expected window twice and checks loaded coverage.
- server / infinite loading rows, error bar, retry button and `oas-rows-error`.
- infinite eviction of the oldest rows does not renumber, and the cursor chain / end signal are unaffected by the buffer cap.

**Must be handled by the host**:

- **Fetcher timeouts**: the component has no built-in timeout; use `AbortSignal.any([signal, AbortSignal.timeout(ms)])` or a manual `AbortController` + timer.
- **Latest-only on raw listeners**: when listening to `oas-window-request` / `oas-rows-request` directly without a helper, maintain your own sequence or `AbortController` and check before refilling.
- **Merge by id**: edit write-backs carry only the loaded slice; replacing `data` wholesale loses unloaded rows — merge by `rowKey` instead of wholesale overwrite.
- **Atomic refill**: write `data` and `window-start` (plus `visual-start` under the visual protocol) in the same synchronous step.
- **Do not write other attributes synchronously in an event listener**: that re-enters rendering; refill after the fetch completes.

Minimal race template for raw listeners (when you do not want a helper):

```ts
let seq = 0
let controller: AbortController | null = null

table.addEventListener('oas-window-request', async (event) => {
  const { start, end } = (event as CustomEvent<{ start: number; end: number }>).detail
  const my = ++seq
  controller?.abort()
  controller = new AbortController()
  const rows = await fetch(`/api/rows?from=${start}&to=${end}`, { signal: controller.signal })
    .then((r) => r.json())
    .catch(() => null)
  if (!rows || my !== seq) return // late / failed: drop
  table.setAttribute('data', JSON.stringify(rows))
  table.setAttribute('window-start', String(start))
})
```

## Related

- Complete windowed recipe (visual protocol and gantt / resource axis expansion): [Server-side windowed data](/en/guide/windowed-data)
- Table protocol details and API: [Table](/en/components/table#server-row-model-row-model-server) · [Infinite scroll](/en/components/table#infinite-scroll-infinite-cursor-pagination) · [Server data approach decision table](/en/components/table#server-data-approach-decision-table)
- How fetched data becomes application state: [State Management Recipes](/en/guide/state-management)
- Lazy-loading components: [Combobox](/en/components/combobox) · [AutoComplete](/en/components/auto-complete) · [Tree](/en/components/tree) · [Cascader](/en/components/cascader)
