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 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:
windowedto enable +total(full row count) +window-start(absolute row index ofdata[0]);datacarries only the slice[window-start, window-start + data.length). - Request:
oas-window-requestwithdetail: { 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
datafirst, thenwindow-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:
infiniteto enable;totaloptional (an unknown total is ended by the host's empty-block signal);max-loaded-rowsoptional (buffer cap; the oldest rows are evicted past the cap, and the cursor chain plus the end signal are unaffected). - Request:
oas-rows-requestwithreason=load-moreanddetail.cursorechoing the cursor recorded by the lastappendRows(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 thedataattribute — writingdataresets the loaded buffer. - Failure:
reportRowsError({ requestId, reason?, error? })feeds the built-in error bar +oas-rows-error+ retry button. - Built in: monotonic
requestId;appendRowssequence 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
requestIdback toappendRows/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-bytogether switches to the server grouping protocol (the host returns mixed rows withkind: 'group'). - Request:
oas-rows-requestwithdetail: { requestId, start, end, sortModel, filterValues, reason, totalKnown, groupBy? };reason=init/paginate/sort/filter/group/refresh. Sort / filter / page-size / group-key changes resetcurrentto 1 before requesting. - Refill: write
dataandtotal; on failure usereportRowsErrorto 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:
requestIdsequence 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
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 bookkeepingThe 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:
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
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-flightThe 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 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.loadingis how the host tells the component a request is in flight. - Tree / cascader own their loading state:
oas-loadfires once when an unloaded node is expanded; after refilling, the host must resetdata(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;reportRowsErroronly takes effect while the id is still the latest. appendRowsrequestId 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 manualAbortController+ timer. - Latest-only on raw listeners: when listening to
oas-window-request/oas-rows-requestdirectly without a helper, maintain your own sequence orAbortControllerand check before refilling. - Merge by id: edit write-backs carry only the loaded slice; replacing
datawholesale loses unloaded rows — merge byrowKeyinstead of wholesale overwrite. - Atomic refill: write
dataandwindow-start(plusvisual-startunder 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):
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
- Table protocol details and API: Table · Infinite scroll · Server data approach decision table
- How fetched data becomes application state: State Management Recipes
- Lazy-loading components: Combobox · AutoComplete · Tree · Cascader