TinyBase logoTinyBase

addResultTableListener

The addResultTableListener method registers a listener function with the Queries object that will be called whenever data in a ResultTable changes.

addResultTableListener(
  queryId: IdOrNull,
  listener: ResultTableListener,
): string
TypeDescription
queryIdIdOrNull

The Id of the query to listen to, or null as a wildcard.

listenerResultTableListener

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

returnsstring

A unique Id for the listener that can later be used to remove it.

The provided listener is a ResultTableListener function, and will be called with a reference to the Queries object, the Id of the ResultTable that changed (which is also the query Id), and a GetResultCellChange function in case you need to inspect any changes that occurred.

You can either listen to a single ResultTable (by specifying a query Id as the method's first parameter) or changes to any ResultTable (by providing a null wildcard).

Examples

This example registers a listener that responds to any changes to a specific ResultTable.

import {createQueries, createStore} from 'tinybase';

const store = createStore().setTable('pets', {
  fido: {species: 'dog', color: 'brown'},
  felix: {species: 'cat', color: 'black'},
  cujo: {species: 'dog', color: 'black'},
});

const queries = createQueries(store).setQueryDefinition(
  'dogColors',
  'pets',
  ({select, where}) => {
    select('color');
    where('species', 'dog');
  },
);

const listenerId = queries.addResultTableListener(
  'dogColors',
  (queries, tableId, getCellChange) => {
    console.log('dogColors result table changed');
    console.log(getCellChange('dogColors', 'fido', 'color'));
  },
);

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

store.delListener(listenerId);

This example registers a listener that responds to any changes to any ResultTable.

import {createQueries, createStore} from 'tinybase';

const store = createStore().setTable('pets', {
  fido: {species: 'dog', color: 'brown'},
  felix: {species: 'cat', color: 'black'},
  cujo: {species: 'dog', color: 'black'},
});

const queries = createQueries(store)
  .setQueryDefinition('dogColors', 'pets', ({select, where}) => {
    select('color');
    where('species', 'dog');
  })
  .setQueryDefinition('catColors', 'pets', ({select, where}) => {
    select('color');
    where('species', 'cat');
  });

const listenerId = queries.addResultTableListener(
  null,
  (queries, tableId) => {
    console.log(`${tableId} result table changed`);
  },
);

store.setCell('pets', 'fido', 'color', 'walnut');
// -> 'dogColors result table changed'
store.setCell('pets', 'felix', 'color', 'tortoiseshell');
// -> 'catColors result table changed'

store.delListener(listenerId);

Since

v2.0.0