Documentation
Cloud Firestore, the database of Firebase, keeps documents in collections and tells a listening app about every change. This tutorial shows the two ways to put a collection in a jqxGrid: a live grid that holds the latest orders and changes with the database, and a grid that reads a large collection a page at a time with query cursors. Edits are written back to the documents, and the database's security rules decide what is accepted.

You need a Firebase project with Cloud Firestore (console.firebase.google.com), or the Firestore emulator on your computer: npx firebase-tools emulators:start --only firestore --project demo-jqwidgets (it needs Java 21). The examples use the emulator and a collection orders with fields customer, product, quantity, price, orderDate (a timestamp) and status. The pages are plain HTML files that load jQWidgets from jsDelivr and the Firebase SDK from Google's CDN.
The Firebase SDK is a set of ES modules, so the script is <script type="module">. Your app's configuration is under Project settings > General > Your apps in the console; with the emulator, a project id starting with demo- is enough.
import { initializeApp } from 'https://www.gstatic.com/firebasejs/13.0.0/firebase-app.js';
import {
getFirestore, connectFirestoreEmulator, collection, query, orderBy, limit, onSnapshot, doc, updateDoc
} from 'https://www.gstatic.com/firebasejs/13.0.0/firebase-firestore.js';
// Your web app's configuration: Project settings > General > Your apps in the Firebase
// console. (A project id that starts with "demo-" works with the emulator only.)
const firebaseConfig = {
projectId: 'demo-jqwidgets'
// apiKey, authDomain, appId ... for a real project
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
// The local emulator (firebase emulators:start); leave this line out for your project.
connectFirestoreEmulator(db, '127.0.0.1', 8080);
The grid is bound to a local array, so it sorts, filters and pages in the browser. toRow turns a document into a row: its id, its fields, and the Firestore Timestamp as a JavaScript Date, which the date column formats and filters.
// A document as a grid row: its id, its fields, and the Timestamp as a Date
const toRow = (snapshot) => {
const data = snapshot.data();
return { id: snapshot.id, ...data, orderDate: data.orderDate.toDate() };
};
onSnapshot listens to a query: the latest 500 orders. Its first answer fills the grid; each later one carries only the documents that were added, changed or removed, and the grid applies them by document id with addrow, updaterow and deleterow. When a new order arrives, the oldest of the 500 leaves the query and its row goes.
// The latest 500 orders, live: the first snapshot fills the grid, each later one brings
// only what changed. Edits, by this page or anyone else, arrive the same way.
let applying = false;
let loaded = false;
const latest = query(collection(db, 'orders'), orderBy('orderDate', 'desc'), limit(500));
onSnapshot(latest, (snapshot) => {
if (!loaded) {
source.localdata = snapshot.docs.map(toRow);
grid.jqxGrid('updatebounddata');
loaded = true;
return;
}
applying = true;
for (const change of snapshot.docChanges()) {
if (change.type === 'added') grid.jqxGrid('addrow', change.doc.id, toRow(change.doc), 'first');
if (change.type === 'modified') grid.jqxGrid('updaterow', change.doc.id, toRow(change.doc));
if (change.type === 'removed') grid.jqxGrid('deleterow', change.doc.id);
}
applying = false;
}, (error) => {
status.textContent = `Could not load the orders: ${error.message}`;
});
The source uses the document id as the row id (id: 'id'), which is what lets each change find its row:
const source = {
datatype: 'array',
localdata: [],
id: 'id',
datafields: [
{ name: 'id', type: 'string' },
{ name: 'customer', type: 'string' },
{ name: 'product', type: 'string' },
{ name: 'quantity', type: 'number' },
{ name: 'price', type: 'number' },
{ name: 'orderDate', type: 'date' },
{ name: 'status', type: 'string' }
]
};
A changed cell is written to its document with updateDoc. Firestore shows the new value at once, before the server answers. If the security rules refuse the write, Firestore takes it back, and the snapshot listener of step 2 puts the old value into the cell; the page only reports why.
// An edit is written to its document. Firestore shows it at once, and takes it back if
// the security rules refuse it (the snapshot listener above brings the old value).
async function saveEdit({ datafield, rowindex, newvalue }) {
const row = grid.jqxGrid('getrowdata', rowindex);
try {
await updateDoc(doc(db, 'orders', row.id), { [datafield]: newvalue });
status.textContent = 'Saved.';
} catch (error) {
status.textContent = `Not saved: ${error.message}`;
}
}
grid.on('cellvaluechanged', (event) => {
if (!applying) saveEdit(event.args);
});
The rules are the real protection, since anyone can change a page's script. These allow reading orders and changing only their quantity (a whole number above 0) and status (one of four values):
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Anyone may read orders and change their quantity and status (the tutorial's grid);
// a real app checks request.auth here.
match /orders/{orderId} {
allow read: if true;
allow update: if request.resource.data.diff(resource.data).affectedKeys().hasOnly(['quantity', 'status'])
&& request.resource.data.quantity is int && request.resource.data.quantity > 0
&& request.resource.data.status in ['New', 'Shipped', 'Delivered', 'Cancelled'];
allow create: if request.resource.data.keys().hasAll(['customer', 'product', 'quantity', 'price', 'orderDate', 'status'])
&& request.resource.data.orderDate is timestamp;
allow delete: if true;
}
}
}
Deploy them with firebase deploy --only firestore:rules; the emulator reads them from firestore.rules next to firebase.json. A quantity of 2.5 entered through the grid's API is refused by the rules, and the cell shows the old quantity again.
A live query that holds the whole collection is right for hundreds or a few thousand documents. For more, read one page at a time. Firestore has no offsets: a page starts after a document, the last one of the page before it. The grid runs in virtual mode with loadServerData, and the function keeps the last document of each page it has read, so the next page is one query and a jump ahead reads the pages in between once.
// Firestore pages with cursors, not offsets: a page starts after the last document of
// the page before it. lastDocs[n] is the last document of page n, for the current sort
// and page size; going to a page further on reads the pages in between once. The
// count is an aggregation query: it is billed as one read per 1,000 documents.
let lastDocs = [];
let order = '';
let total = 0;
async function loadPage(params) {
const field = sortable.has(params.sortdatafield) && params.sortorder ? params.sortdatafield : 'orderDate';
const direction = params.sortorder === 'asc' ? 'asc' : 'desc';
if (order !== `${field} ${direction} ${params.pagesize}`) {
order = `${field} ${direction} ${params.pagesize}`;
lastDocs = [];
total = (await getCountFromServer(orders)).data().count;
}
const sorted = query(orders, orderBy(field, direction));
let page = null;
for (let n = Math.min(lastDocs.length, params.pagenum); n <= params.pagenum; n++) {
const after = n > 0 ? [startAfter(lastDocs[n - 1])] : [];
page = await getDocs(query(sorted, ...after, limit(params.pagesize)));
if (page.docs.length) lastDocs[n] = page.docs[page.docs.length - 1];
}
const records = page.docs.map((d) => ({ id: d.id, ...d.data(), orderDate: d.data().orderDate.toDate() }));
return { records, totalrecords: total };
}
The source and adapter are those of the server-side tutorials. Sorting is done by Firestore, so a new sort starts a new list of cursors:
const source = {
// (json: the adapter asks for data through loadServerData, which an array source never does)
datatype: 'json',
id: 'id',
datafields: [
{ name: 'id', type: 'string' },
{ name: 'customer', type: 'string' },
{ name: 'product', type: 'string' },
{ name: 'quantity', type: 'number' },
{ name: 'price', type: 'number' },
{ name: 'orderDate', type: 'date' },
{ name: 'status', type: 'string' }
],
// The adapter needs a url to ask for data; loadServerData below does the asking.
url: 'orders',
totalrecords: 0,
// Sorting happens in Firestore: ask again.
sort: () => grid.jqxGrid('updatebounddata', 'sort')
};
const adapter = new $.jqx.dataAdapter(source, {
loadServerData: (params, settings, callback) => {
loadPage(params).then((result) => {
status.textContent = '';
adapter.totalrecords = result.totalrecords;
callback(result);
}, (error) => {
status.textContent = `Could not load the orders: ${error.message}`;
callback({ records: [], totalrecords: 0 });
});
}
});
Firestore sorts by one field here without extra setup. Sorting by one field and filtering by another needs a composite index: Firestore's error message has a link that creates it. getCountFromServer counts without reading the documents; it is read again only when the sort or page size changes.
The live grid, firebase.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Orders from Cloud Firestore</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/styles/jqx.base.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/styles/jqx.fluent.css">
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxcore.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxdata.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxbuttons.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxscrollbar.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxmenu.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxlistbox.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxdropdownlist.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxcalendar.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxdatetimeinput.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxnumberinput.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxgrid.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxgrid.selection.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxgrid.edit.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxgrid.sort.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxgrid.filter.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxgrid.pager.js"></script>
</head>
<body>
<main style="padding: 16px;">
<h1>Orders</h1>
<p id="status" role="status"></p>
<div id="grid"></div>
</main>
<script type="module">
import { initializeApp } from 'https://www.gstatic.com/firebasejs/13.0.0/firebase-app.js';
import {
getFirestore, connectFirestoreEmulator, collection, query, orderBy, limit, onSnapshot, doc, updateDoc
} from 'https://www.gstatic.com/firebasejs/13.0.0/firebase-firestore.js';
// Your web app's configuration: Project settings > General > Your apps in the Firebase
// console. (A project id that starts with "demo-" works with the emulator only.)
const firebaseConfig = {
projectId: 'demo-jqwidgets'
// apiKey, authDomain, appId ... for a real project
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
// The local emulator (firebase emulators:start); leave this line out for your project.
connectFirestoreEmulator(db, '127.0.0.1', 8080);
const grid = $('#grid');
const status = document.getElementById('status');
// A document as a grid row: its id, its fields, and the Timestamp as a Date
const toRow = (snapshot) => {
const data = snapshot.data();
return { id: snapshot.id, ...data, orderDate: data.orderDate.toDate() };
};
const source = {
datatype: 'array',
localdata: [],
id: 'id',
datafields: [
{ name: 'id', type: 'string' },
{ name: 'customer', type: 'string' },
{ name: 'product', type: 'string' },
{ name: 'quantity', type: 'number' },
{ name: 'price', type: 'number' },
{ name: 'orderDate', type: 'date' },
{ name: 'status', type: 'string' }
]
};
grid.jqxGrid({
theme: 'fluent',
width: '100%',
height: 560,
source: new $.jqx.dataAdapter(source),
pageable: true,
pagesize: 20,
sortable: true,
filterable: true,
showfilterrow: true,
editable: true,
selectionmode: 'singlecell',
columns: [
{ text: 'Customer', datafield: 'customer', width: 180, editable: false },
{ text: 'Product', datafield: 'product', width: 120, editable: false },
{
text: 'Quantity', datafield: 'quantity', width: 90, cellsalign: 'right', align: 'right', filtertype: 'number',
columntype: 'numberinput',
createeditor: (row, value, editor) => editor.jqxNumberInput({ decimalDigits: 0, min: 1, spinButtons: true }),
validation: (cell, value) => (Number.isInteger(value) && value > 0) || { result: false, message: 'A whole number above 0' }
},
{ text: 'Price', datafield: 'price', width: 90, cellsalign: 'right', align: 'right', cellsformat: 'c2', filtertype: 'number', editable: false },
{ text: 'Date', datafield: 'orderDate', width: 110, cellsformat: 'yyyy-MM-dd', filtertype: 'range', editable: false },
{
text: 'Status', datafield: 'status', filtertype: 'list', filteritems: ['New', 'Shipped', 'Delivered', 'Cancelled'],
columntype: 'dropdownlist',
createeditor: (row, value, editor) => editor.jqxDropDownList({ source: ['New', 'Shipped', 'Delivered', 'Cancelled'], autoDropDownHeight: true })
}
]
});
// The latest 500 orders, live: the first snapshot fills the grid, each later one brings
// only what changed. Edits, by this page or anyone else, arrive the same way.
let applying = false;
let loaded = false;
const latest = query(collection(db, 'orders'), orderBy('orderDate', 'desc'), limit(500));
onSnapshot(latest, (snapshot) => {
if (!loaded) {
source.localdata = snapshot.docs.map(toRow);
grid.jqxGrid('updatebounddata');
loaded = true;
return;
}
applying = true;
for (const change of snapshot.docChanges()) {
if (change.type === 'added') grid.jqxGrid('addrow', change.doc.id, toRow(change.doc), 'first');
if (change.type === 'modified') grid.jqxGrid('updaterow', change.doc.id, toRow(change.doc));
if (change.type === 'removed') grid.jqxGrid('deleterow', change.doc.id);
}
applying = false;
}, (error) => {
status.textContent = `Could not load the orders: ${error.message}`;
});
// An edit is written to its document. Firestore shows it at once, and takes it back if
// the security rules refuse it (the snapshot listener above brings the old value).
async function saveEdit({ datafield, rowindex, newvalue }) {
const row = grid.jqxGrid('getrowdata', rowindex);
try {
await updateDoc(doc(db, 'orders', row.id), { [datafield]: newvalue });
status.textContent = 'Saved.';
} catch (error) {
status.textContent = `Not saved: ${error.message}`;
}
}
grid.on('cellvaluechanged', (event) => {
if (!applying) saveEdit(event.args);
});
</script>
</body>
</html>
The paged grid, firebase-pages.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Orders from Cloud Firestore, a page at a time</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/styles/jqx.base.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/styles/jqx.fluent.css">
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxcore.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxdata.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxbuttons.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxscrollbar.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxmenu.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxlistbox.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxdropdownlist.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxgrid.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxgrid.selection.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxgrid.sort.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jqwidgets-scripts@27/jqwidgets/jqxgrid.pager.js"></script>
</head>
<body>
<main style="padding: 16px;">
<h1>Orders</h1>
<p id="status" role="status"></p>
<div id="grid"></div>
</main>
<script type="module">
import { initializeApp } from 'https://www.gstatic.com/firebasejs/13.0.0/firebase-app.js';
import {
getFirestore, connectFirestoreEmulator, collection, query, orderBy, limit, startAfter, getDocs, getCountFromServer
} from 'https://www.gstatic.com/firebasejs/13.0.0/firebase-firestore.js';
const app = initializeApp({ projectId: 'demo-jqwidgets' });
const db = getFirestore(app);
connectFirestoreEmulator(db, '127.0.0.1', 8080);
const grid = $('#grid');
const status = document.getElementById('status');
const orders = collection(db, 'orders');
const sortable = new Set(['customer', 'product', 'quantity', 'price', 'orderDate']);
// Firestore pages with cursors, not offsets: a page starts after the last document of
// the page before it. lastDocs[n] is the last document of page n, for the current sort
// and page size; going to a page further on reads the pages in between once. The
// count is an aggregation query: it is billed as one read per 1,000 documents.
let lastDocs = [];
let order = '';
let total = 0;
async function loadPage(params) {
const field = sortable.has(params.sortdatafield) && params.sortorder ? params.sortdatafield : 'orderDate';
const direction = params.sortorder === 'asc' ? 'asc' : 'desc';
if (order !== `${field} ${direction} ${params.pagesize}`) {
order = `${field} ${direction} ${params.pagesize}`;
lastDocs = [];
total = (await getCountFromServer(orders)).data().count;
}
const sorted = query(orders, orderBy(field, direction));
let page = null;
for (let n = Math.min(lastDocs.length, params.pagenum); n <= params.pagenum; n++) {
const after = n > 0 ? [startAfter(lastDocs[n - 1])] : [];
page = await getDocs(query(sorted, ...after, limit(params.pagesize)));
if (page.docs.length) lastDocs[n] = page.docs[page.docs.length - 1];
}
const records = page.docs.map((d) => ({ id: d.id, ...d.data(), orderDate: d.data().orderDate.toDate() }));
return { records, totalrecords: total };
}
const source = {
// (json: the adapter asks for data through loadServerData, which an array source never does)
datatype: 'json',
id: 'id',
datafields: [
{ name: 'id', type: 'string' },
{ name: 'customer', type: 'string' },
{ name: 'product', type: 'string' },
{ name: 'quantity', type: 'number' },
{ name: 'price', type: 'number' },
{ name: 'orderDate', type: 'date' },
{ name: 'status', type: 'string' }
],
// The adapter needs a url to ask for data; loadServerData below does the asking.
url: 'orders',
totalrecords: 0,
// Sorting happens in Firestore: ask again.
sort: () => grid.jqxGrid('updatebounddata', 'sort')
};
const adapter = new $.jqx.dataAdapter(source, {
loadServerData: (params, settings, callback) => {
loadPage(params).then((result) => {
status.textContent = '';
adapter.totalrecords = result.totalrecords;
callback(result);
}, (error) => {
status.textContent = `Could not load the orders: ${error.message}`;
callback({ records: [], totalrecords: 0 });
});
}
});
grid.jqxGrid({
theme: 'fluent',
width: '100%',
height: 560,
source: adapter,
virtualmode: true,
rendergridrows: (params) => params.data,
pageable: true,
pagesize: 20,
sortable: true,
columns: [
{ text: 'Customer', datafield: 'customer', width: 180 },
{ text: 'Product', datafield: 'product', width: 120 },
{ text: 'Quantity', datafield: 'quantity', width: 90, cellsalign: 'right', align: 'right' },
{ text: 'Price', datafield: 'price', width: 90, cellsalign: 'right', align: 'right', cellsformat: 'c2' },
{ text: 'Date', datafield: 'orderDate', width: 110, cellsformat: 'yyyy-MM-dd' },
{ text: 'Status', datafield: 'status', sortable: false }
]
});
</script>
</body>
</html>
Start the emulator and add some orders (the emulator's UI, or a short script with addDoc), then open firebase.html. Change a document in the Firebase console or the emulator UI: its row changes in the grid. Add an order dated today: it appears at the top. In firebase-pages.html, go to page 3, then click the Quantity header: Firestore sorts and the grid shows page 3 of the new order.