useGrist
The widget's one object for Grist: connection, records, mapping, writes, options, linking and REST.
widget.useGrist(): UseGristResult // typed from the declaration
useGrist(): UseGristResult // the same, untypeduseGrist() reads the connection of the <GristWidgetProvider> above it:
the one mountGristWidget() renders inside Grist, and
renderWithGrist(<App />, { widget }) in a test. The access level and
columns are the widget's declaration, from defineGristWidget(), whose
widget.useGrist() is the same hook typed from it. Outside a provider
useGrist() throws; a component that also runs outside Grist calls
useGristOptional(), which returns null there.
Every call reads one store through useSyncExternalStore: a component
re-renders when a value changes. Every method is referentially stable for the
widget's lifetime, so it is safe in effect dependencies; the result object
itself is new on every change, so depend on its members, not on it.
UseGristOptions
type UseGristOptions = GristReadyOptions & {
requiredLinking?: "target" | "source" // the link it can't work without: an alert when it is missing
suppressAlerts?: GristSdkAlertKind[] // alert kinds mountGristWidget() never shows, e.g. ["cell-issues"]
schema?: StandardSchema // extra rules for the mapped records (zod 4, valibot, arktype…)
optionsVersion?: number // the version of the widget options it reads and writes
migrate?: MigrateWidgetOptions // brings older options to optionsVersion, on read
}GristReadyOptions is what Grist's ready() takes: requiredAccess
("none", "read table", "full"), columns to map, allowSelectBy,
hasCustomOptions, onEditOptions. See
Provider & boundary.
UseGristResult<TRow, TMapped>
The access column is the least access a member needs. A member that needs
"full" fails in a widget that asked for less, and the alert above the
widget says what to change in Grist.
Connection
| Member | Type | Notes |
|---|---|---|
status | "booting" | "ready" | "unavailable" | "error" | "error" too when Grist grants less access than declared. |
error | string | null | Why the widget can't run, else null. |
reload() | () => Promise<void> | Calls grist.ready() again and re-reads mappings. |
theme | "light" | "dark" | null | Grist's theme, null until Grist sends it. |
Selection and mapping ("read table")
| Member | Type | Notes |
|---|---|---|
record | GristRowRecord<TRow> | null | The selected row, raw column ids. |
records | GristRowRecord<TRow>[] | null | The section's rows (what its filters show). |
mode | "empty" | "row" | "new-row" | No row, a row, or the add-row placeholder. |
currentTableId | string | null | The section's table. |
mappings | GristWidgetColumnMap | Declared name → the Grist column id(s) mapped to it. |
columnMappingStatus | { ok, pending?, missing, emptyMultiples } | pending until Grist reports mappings; ok once every required column is mapped. |
mappedRecord | TMapped | null | The selected row under declared names, as Grist's mapColumnNames builds it (id, each mapped column, a list for allowMultiple), each cell the value its declared type promises; null while a required column isn't mapped. See Typed reads. |
mappedRecords | TMapped[] | null | Every row of the section, like mappedRecord. |
cellIssues | readonly GristCellIssue[] | The mapped cells that don't match their declared type (or schema): { rowId, column, message, value }. Such a cell is null in the mapped records. |
resolveMappedColumnId(name) | (name: string) => string | The Grist column id mapped to name, or name. |
mapBack(patch) | (patch: Partial<TMapped>) => Record<string, unknown> | A patch under declared names as real column ids, each value encoded for its declared type (a list to ["L", ...], a Date to seconds); allowMultiple columns can't be written back and are skipped (an alert names them). |
updateRecord(patch), updateRecord(rowId, patch) | Promise<void> | Writes a patch under declared names to the selected row (or to rowId): mapBack and table.update in one call. Rejects when no row is selected and none is given. |
addRecord(patch) | Promise<number> | Adds a row to the section's table from a patch under declared names; resolves to its row id. |
Reads
| Member | Access | Notes |
|---|---|---|
fetchRows(options?) | "read table" | The section's rows (what its filters show, in its order), each { id, ...cells } under real column ids. |
fetchRows(tableId, options?) | "full" | Any table's rows, in Grist's order (order: "id" or "none" to change it; columns to decode with the replica's column metadata). |
fetchRows(…, { columnar: true }) | as above | Grist's column-oriented payload ({ id: [...], Name: [...] }) instead. |
listTables(options?) | "full" | Table ids; Grist's own tables only with { includeSystem: true }. |
listColumns(tableId, options?) | "full" | Column ids, types, labels, formulas; each column's settings (widgetOptions, such as a Choice column's choices), and for a Ref or RefList column the referenced table's column it shows (visibleCol). |
Writes ("full")
| Member | Notes |
|---|---|
table | create, update, upsert, destroy on the section's table (single or bulk). |
getTable(tableId) | The same, on any table. |
applyActions(actions, options?) | User actions applied together, e.g. schema changes with the user action builders. |
readOnly | true when Grist opened the document read-only (a viewer, view mode, a snapshot): every write above is refused without reaching Grist ("No write access"), and the read-only alert says so. Disable what would write. Widget options still save. It tells the interface what to offer; Grist itself enforces who may write. |
actionStatus | "idle" | "running" | "error": the last write. |
actionError | The last failed write's message, else null. |
Widget options
| Member | Access | Notes |
|---|---|---|
widgetOptions | "read table" | The options Grist stores for this widget, null until it sends them. With optionsVersion, migrated and without the version key. |
optionsIssue | "read table" | Why the widget may not write over its options (written by a newer version, or not migrated), or null. |
setWidgetOptions(options) | "full" | Replaces them (under optionsVersion, if declared); rejects while optionsIssue is set, except setWidgetOptions({}), which resets them. |
patchWidgetOptions(patch) | "full" | Merges patch into them, as the widget reads them; rejects while optionsIssue is set. |
configurationOpen | "none" | true while the widget's configuration is open: Grist's "Open configuration" (with hasCustomOptions: true) or openConfiguration() opened it. With an exported Settings, mountGristWidget() draws the view (Widget options). |
optionsDraft | "none" | true once the widget's own write to its options comes back: Grist holds it as a draft of the section until its Save. false again on Grist's Revert, and when the configuration opens or closes (Grist tells a widget nothing on Save). |
openConfiguration() | "none" | Opens it from the widget, as Grist's button does. |
closeConfiguration() | "none" | Closes it: the view's close button, Escape, Cancel, or once its settings are saved. |
Linking ("read table")
| Member | Notes |
|---|---|
setCursorPosition(pos) | Moves Grist's cursor ({ rowId?, field?, sectionId? }). |
setLinkedRowSelection(rowIds | null) | The rows the widget selects, for sections linked to it (allowSelectBy: true). |
Attachments and REST ("full")
| Member | Notes |
|---|---|
getAttachmentUrl(id, options?) | A download URL carrying an access token. |
fetchAttachmentBlob(id, options?) | { blob, contentType }. |
uploadAttachment(file, options?) | { ids, firstId }: put them in an Attachments cell with gristAttachmentCellValue(). |
fetchWithAuth(path, init?) | fetch() against the document's REST API (/records, /sql, …) with an access token. Only the document's own Grist instance gets the token: another origin throws. |
options.readOnly asks for a read-only token on the download and REST
members.
Outside a provider
useGristOptional() returns null outside <GristWidgetProvider>, for a
component that also works without Grist.
import { useGristOptional } from "grist-widget-sdk"
export function TableName() {
const w = useGristOptional()
return <span>{w ? w.currentTableId ?? "…" : "Not in Grist"}</span>
}Examples
Selection + write
import { defineGristWidget } from "grist-widget-sdk"
export const widget = defineGristWidget({
requiredAccess: "full",
columns: [{ name: "Done", type: "Bool" }],
})
function Toggle() {
const w = widget.useGrist()
if (w.mode !== "row" || !w.mappedRecord) return null
const done = w.mappedRecord.Done ?? false
return (
<button disabled={w.actionStatus === "running"} onClick={() => w.updateRecord({ Done: !done })}>
{done ? "Mark not done" : "Mark done"}
</button>
)
}Status + retry
function StatusLine() {
const { status, error, reload } = useGrist()
if (status === "ready") return null
if (status === "error") return (
<p>Error: {error} <button onClick={reload}>Retry</button></p>
)
if (status === "unavailable") return <p>Open this widget inside a Grist document.</p>
return <p>Connecting…</p>
}Schema mutation
import { gristAddColumnAction, gristRenameColumnAction } from "grist-widget-sdk/actions"
async function migrate(w: ReturnType<typeof useGrist>) {
await w.applyActions(
[
gristAddColumnAction("Tasks", "Priority", { type: "Choice" }),
gristRenameColumnAction("Tasks", "Title", "Name"),
],
{ desc: "Add Priority column" },
)
}REST
const r = await w.fetchWithAuth("/sql", {
method: "POST",
body: JSON.stringify({ sql: "SELECT id, Name FROM Tasks LIMIT 5" }),
})
const data = await r.json()