Server data
When there are tens of thousands of rows or more, do not fetch them all at once. With the dataSource option, the grid asks the server for only what it needs. As the scroll nears the end, it fetches the next batch and appends it (infinite scroll). There is no page-number bar.
import { createGrid } from 'horee-grid'
// Fake server for the example: sorts and filters 100,000 records and returns only what was asked (use fetch in real code)
const DB = Array.from({ length: 100000 }, (_, i) => ({
id: i + 1,
doc: `INV-${String(i + 1).padStart(6, '0')}`,
vendor: `Vendor ${(i * 31) % 977}`,
amount: (((i * 7919) % 99000) + 1000) * 10
}))
async function fakeApi({ offset, limit, sort, filters }) {
await new Promise(r => setTimeout(r, 250))
let list = DB
for (const f of filters) if (f.op === 'contains') list = list.filter(r => String(r[f.field]).includes(f.value))
if (sort[0]) {
const { field, dir } = sort[0]
list = [...list].sort((a, b) => (a[field] > b[field] ? 1 : a[field] < b[field] ? -1 : 0) * (dir === 'asc' ? 1 : -1))
}
const sum = list.reduce((s, r) => s + r.amount, 0)
return { rows: list.slice(offset, limit ? offset + limit : undefined), total: list.length, sum }
}
const grid = createGrid(host, {
locale: 'en',
rowKey: 'id',
columns: [
{ field: 'doc', title: 'Doc no.', width: 130 },
{ field: 'vendor', title: 'Vendor', flex: 1 },
{ field: 'amount', title: 'Amount', type: 'number', width: 140 }
],
dataSource: {
pageSize: 200,
load: async req => {
const r = await fakeApi(req)
return { rows: r.rows, total: r.total, bottomRows: [{ vendor: 'Grand total', amount: r.sum }] }
}
},
onLoad: info => {
const total = info.total == null ? '?' : info.total.toLocaleString()
toolbar.querySelector('.ex-out').textContent = `${info.loaded.toLocaleString()} / ${total} rows` + (info.loading ? ' · loading' : '')
}
})
toolbar.innerHTML = `<button data-a="reload">Load</button><span class="ex-out"></span>`
toolbar.onclick = e => e.target.dataset.a === 'reload' && grid.reload()
grid.reload()Basic shape
const grid = createGrid(host, {
columns,
rowKey: 'id',
dataSource: {
pageSize: 200,
load: async req => {
const res = await fetch('/api/invoices', { method: 'POST', body: JSON.stringify({ ...searchForm, page: req }) })
const data = await res.json()
return { rows: data.rows, total: data.total }
}
}
})
searchButton.onclick = () => grid.reload() // searchreload()fetches the first batch. Your screen must call it once at the start.- After that, the grid calls
loadby itself as the user scrolls, sorts and filters. - Search conditions (period, vendor …) are added by your screen inside
load. The grid does not know about them.
Request: PageRequest
{
offset: 400, // rows to skip (rows received so far)
limit: 200, // rows to fetch. 0 = all matching rows (Excel download)
sort: [{ id: 'amount', field: 'amount', dir: 'desc' }],
filters: [{ id: 'vendor', field: 'vendor', op: 'contains', value: 'Trading' }]
}fieldis the column'sfield; use it as the server column name. Columns without afield, such as calculated columns, are left out.- Filter values for date columns are sent as
yyyymmdd. Whatever shape the user typed, the server receives only one. opis one of the 11 grid filter conditions.
field in sort and filters comes from the browser. Before putting it into SQL, check that it is an allowed column name, and pass values as bind variables.
Server-side example (SQL)
select *, count(*) over () as total
from invoices
where vendor ilike '%' || :v || '%' -- from filters
order by amount desc -- from sort (after checking the allow list)
offset :offset limit :limit -- drop the limit clause when limit is 0Response: PageResult
{
rows: [...], // this batch
total: 128450, // total matching rows (read only from the first batch)
bottomRows: [{ vendor: 'Total', amount: 9182733000 }] // fixed bottom rows (replaced when given with the first batch)
}- With
total, the grid fetches up to that count. Without it, a batch smaller thanlimitis treated as the end. - Totals must cover the whole data set, so the server computes them and returns them in
bottomRows. The grid only knows the rows it has received and cannot compute them.
Showing loading state
createGrid(host, {
columns,
dataSource,
onLoad: ({ loaded, total, loading }) => {
status.textContent = `${loaded.toLocaleString()} / ${total?.toLocaleString() ?? '?'} rows`
}
})
grid.getPageInfo() // the same { loaded, total, loading }While loading, a thin bar runs along the bottom of the grid (.hg-loading).
When cells have been changed
If a user edits cells and then changes the sort or filter, the grid refetches from the first batch and the edits are lost. Ask first with confirmReload.
dataSource: {
load,
confirmReload: () => confirm('You have unsaved changes. Discard them and reload?')
}It is not asked when nothing has changed. Return false to keep the sort and filter unchanged. Returning a Promise (your own confirm dialog) also works.
Errors
If loading started by the grid itself (scrolling, sorting, filtering) fails, onError is called. Errors from reload() are thrown by reload() itself.
dataSource: {
load,
onError: e => toast('Could not load the list: ' + (e as Error).message)
}Things to know
- Received rows all stay in memory. Scroll very far and they pile up.
- The header checkbox and Ctrl+A select only the rows received so far.
- Because paging is
offset-based, rows may repeat or be skipped if server data changes between fetches. For frequently changing lists, pass the query time as a condition as well. - If not everything has been received, the Excel download fetches all rows separately with
limit: 0. Make sure your server can return a very large result at once.