addWillSetRowCallback
The addWillSetRowCallback method registers a WillSetRowCallback that will be called before any Row is set in the Store.
addWillSetRowCallback(callback: WillSetRowCallback): Middleware| Type | Description | |
|---|---|---|
callback | WillSetRowCallback | The |
| returns | Middleware | A reference to the |
The callback can transform the Row or return undefined to prevent the write. Multiple callbacks can be registered and they are called sequentially, each receiving the (possibly transformed) row from the previous callback.
This callback fires both when a whole Row is set with the setRow method, and when a single Cell is set with the setCell method. When called from setCell, the callback receives a prospective row consisting of the existing Cell values merged with the new Cell value. The entire returned Row is then applied as though setRow had been called: all cells in the returned Row are written (each also passing through willSetCell), and any cells absent from the returned Row that existed before will be deleted. Return undefined to cancel the operation entirely.
Examples
This example registers a callback that upper-cases string Cell values in rows set to the 'pets' table.
import {createMiddleware, createStore} from 'tinybase';
const store = createStore();
const middleware = createMiddleware(store);
middleware.addWillSetRowCallback((tableId, _rowId, row) =>
tableId === 'pets'
? Object.fromEntries(
Object.entries(row).map(([k, v]) => [
k,
typeof v === 'string' ? v.toUpperCase() : v,
]),
)
: row,
);
store.setRow('pets', 'fido', {species: 'dog', legs: 4});
console.log(store.getRow('pets', 'fido'));
// -> {species: 'DOG', legs: 4}
middleware.destroy();
This example registers a callback that prevents writes to the 'species' table.
import {createMiddleware, createStore} from 'tinybase';
const store = createStore();
const middleware = createMiddleware(store);
middleware.addWillSetRowCallback((tableId, _rowId, row) =>
tableId === 'species' ? undefined : row,
);
store.setRow('species', 'dog', {legs: 4, sound: 'woof'});
console.log(store.getTables());
// -> {}
middleware.destroy();
This example shows the callback firing when setCell is called, automatically stamping an 'updated' timestamp onto the row each time any cell in it is written.
import {createMiddleware, createStore} from 'tinybase';
const store = createStore();
const middleware = createMiddleware(store);
store.setRow('pets', 'fido', {species: 'dog'});
middleware.addWillSetRowCallback((_tableId, _rowId, row) => ({
...row,
updated: Date.now(),
}));
store.setCell('pets', 'fido', 'legs', 4);
console.log(store.getCell('pets', 'fido', 'legs'));
// -> 4
console.log(typeof store.getCell('pets', 'fido', 'updated'));
// -> 'number'
middleware.destroy();
Since
v8.0.0