subscribe
The subscribe method listens for committed table changes and returns an unsubscribe function. OPFS Clients receive changes from every connected tab. After handover or page restoration, reset events notify every subscriber to re-query even though tables is empty.
subscribe(
options: SubscriptionOptions,
listener: (event: TablesChangedEvent) => void,
): () => void| Type | Description | |
|---|---|---|
options | SubscriptionOptions | |
listener | (event: TablesChangedEvent) => void | |
| returns | () => void | A function that removes this subscription when called. |
Example
import {create} from 'tinyjoin';
const db = await create();
await db.exec(`
CREATE TABLE tasks (id TEXT PRIMARY KEY, title TEXT NOT NULL)
`);
const unsubscribe = db.subscribe({tables: ['tasks']}, async ({tables}) => {
// The event names the tables that changed. Query again for their rows.
const {rows} = await db.query('SELECT * FROM tasks ORDER BY id');
console.log(tables, rows);
// -> ['tasks'] [{id: 'a', title: 'Write docs'}]
unsubscribe();
await db.close();
});
await db.query('INSERT INTO tasks (id, title) VALUES ($1, $2)', [
'a',
'Write docs',
]);