TinyBase logoTinyBase

addTablesListener

The addTablesListener method registers a listener function with the Store that will be called whenever data in the Store changes.

addTablesListener(
  listener: TablesListener<Store>,
  mutator?: boolean,
): string
TypeDescription
listenerTablesListener<Store>

The function that will be called whenever data in the Store changes.

mutator?boolean

An optional boolean that indicates that the listener mutates Store data.

returnsstring

A unique Id for the listener that can later be used to call it explicitly, or to remove it.

The provided listener is a TablesListener function, and will be called with a reference to the Store and a GetCellChange function in case you need to inspect any changes that occurred.

Use the optional mutator parameter to indicate that there is code in the listener that will mutate Store data. If set to false (or omitted), such mutations will be silently ignored. All relevant mutator listeners (with this flag set to true) are called before any non-mutator listeners (since the latter may become relevant due to changes made in the former). The changes made by mutator listeners do not fire other mutating listeners, though they will fire non-mutator listeners.

Examples

This example registers a listener that responds to any changes to the whole Store.

import {createStore} from 'tinybase';

const store = createStore().setTables({
  pets: {fido: {species: 'dog', color: 'brown'}},
});
const listenerId = store.addTablesListener((store, getCellChange) => {
  console.log('Tables changed');
  console.log(getCellChange('pets', 'fido', 'color'));
});

store.setCell('pets', 'fido', 'color', 'walnut');
// -> 'Tables changed'
// -> [true, 'brown', 'walnut']

store.delListener(listenerId);

This example registers a listener that responds to any changes to the whole Store, and which also mutates the Store itself.

import {createStore} from 'tinybase';

const store = createStore().setTables({
  pets: {fido: {species: 'dog', color: 'brown'}},
});
const listenerId = store.addTablesListener(
  (store) => store.setCell('meta', 'update', 'store', true),
  true,
);

store.delCell('pets', 'fido', 'color');
console.log(store.getTable('meta'));
// -> {update: {store: true}}

store.delListener(listenerId);

Since

v1.0.0