addWillSetTablesCallback
The addWillSetTablesCallback method registers a WillSetTablesCallback that will be called before Tables are set in the Store.
addWillSetTablesCallback(callback: WillSetTablesCallback): Middleware| Type | Description | |
|---|---|---|
callback | WillSetTablesCallback | The |
| returns | Middleware | A reference to the |
The callback can transform the Tables or return undefined to prevent the write. Multiple callbacks can be registered and they are called sequentially, each receiving the (possibly transformed) tables from the previous callback.
Examples
This example registers a callback that upper-cases all string Cell values when entire Tables are set in the pet store.
import {createMiddleware, createStore} from 'tinybase';
const store = createStore();
const middleware = createMiddleware(store);
middleware.addWillSetTablesCallback((tables) =>
Object.fromEntries(
Object.entries(tables).map(([tableId, table]) => [
tableId,
Object.fromEntries(
Object.entries(table).map(([rowId, row]) => [
rowId,
Object.fromEntries(
Object.entries(row).map(([k, v]) => [
k,
typeof v === 'string' ? v.toUpperCase() : v,
]),
),
]),
),
]),
),
);
store.setTables({pets: {fido: {species: 'dog'}, felix: {species: 'cat'}}});
console.log(store.getTables());
// -> {pets: {fido: {species: 'DOG'}, felix: {species: 'CAT'}}}
middleware.destroy();
This example registers a callback that prevents setting any Tables that include a 'banned' table.
import {createMiddleware, createStore} from 'tinybase';
const store = createStore();
const middleware = createMiddleware(store);
middleware.addWillSetTablesCallback((tables) =>
'banned' in tables ? undefined : tables,
);
store.setTables({banned: {r1: {c1: 1}}, pets: {fido: {species: 'dog'}}});
console.log(store.getTables());
// -> {}
middleware.destroy();
Since
v8.0.0