You're viewing the v2.3 docs.
Ledger docs
Reference

API reference

The complete public surface of Ledger v2.4. Everything is exported from the package root except framework bindings, which live in ledger/react, ledger/vue, and ledger/svelte.

createLedger()

Creates a store from a map of collections. This is the entry point.

typescript
function createLedger<S extends Schema>(
  collections: S,
  options?: LedgerOptions
): Ledger<S>;

interface LedgerOptions {
  persist?: Adapter;       // storage adapter, default: in-memory
  schemaVersion?: number;  // current schema version, default: 1
  migrations?: Record<number, MigrationFn>;
}
OptionTypeDescription
persistAdapterStorage backend. Omit for in-memory only.
schemaVersionnumberCurrent schema version for migrations.
migrationsRecord<number, fn>Upgrade steps keyed by target version.

Returns a Ledger whose properties are the collections you passed, plus ready (a promise) and flush().

collection()

Declares a typed collection. The generic parameter is the record type.

typescript
function collection<T>(options?: {
  key?: keyof T;           // primary key field, default: 'id'
  index?: (keyof T)[];     // fields to build secondary indexes on
}): Collection<T>;
OptionTypeDefault
keykeyof T'id'
index(keyof T)[][]

Collection methods

MethodReturnsDescription
insert(record)TAdd a record. Throws if the key exists.
upsert(record)TInsert or replace by key.
update(key, patch)TShallow-merge a partial into a record.
unset(key, field)TDelete a single field from a record.
remove(key)booleanDelete a record by key.
get(key)T | undefinedRead one record by key.
all()T[]Snapshot of every record.
where(fn)Query<T>Start a filtered query.
onChange(fn)() => voidSubscribe to a raw change feed.

where()

Filters records by a predicate and returns a chainable query.

typescript
where(predicate: (record: T) => boolean): Query<T>;

// Example
db.users.where((u) => u.role === 'admin' && u.active);

live()

Turns a query into a reactive subscription. The callback fires immediately and on every change to the result.

typescript
live(): LiveQuery<T>;

interface LiveQuery<T> {
  subscribe(fn: (records: T[]) => void): () => void;
  all(): T[];
}

// Example
const stop = db.users.where((u) => u.active).live().subscribe(render);
stop(); // unsubscribe

subscribe returns its unsubscribe function. Call it to stop receiving updates and free the query.

React binding

The useQuery hook subscribes on mount and unsubscribes on unmount.

tsx
import { useQuery } from 'ledger/react';

function useQuery<T>(factory: () => LiveQuery<T>, deps?: unknown[]): T[];

// Example
const admins = useQuery(() => db.users.where((u) => u.role === 'admin').live());
Esc
↑↓ navigate ↵ open Esc close