TinyBase logoTinyBase

addResultRowIdsListener

The addResultRowIdsListener method registers a listener function with the Queries object that will be called whenever the ResultRow Ids in a ResultTable change.

addResultRowIdsListener(
  queryId: IdOrNull,
  listener: ResultRowIdsListener,
): Id
TypeDescription
queryIdIdOrNull

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

listenerResultRowIdsListener

The function that will be called whenever the ResultRow Ids in the ResultTable change.

returnsId

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

The provided listener is a ResultRowIdsListener function, and will be called with a reference to the Queries object and the Id of the ResultTable that changed (which is also the query Id).

By default, such a listener is only called when a ResultRow is added to, or removed from, the ResultTable. To listen to all changes in the ResultTable, use the addResultTableListener method.

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 change to the ResultRow Ids of a specific ResultTable.

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.addResultRowIdsListener(
  'dogColors',
  (queries, tableId) => {
    console.log(`Row Ids for dogColors result table changed`);
    console.log(queries.getResultRowIds('dogColors'));
  },
);

store.setRow('pets', 'rex', {species: 'dog', color: 'tan'});
// -> 'Row Ids for dogColors result table changed'
// -> ['fido', 'cujo', 'rex']

store.delListener(listenerId);

This example registers a listener that responds to any change to the ResultRow Ids of any ResultTable.

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.addResultRowIdsListener(
  null,
  (queries, tableId) => {
    console.log(`Row Ids for ${tableId} result table changed`);
  },
);

store.setRow('pets', 'rex', {species: 'dog', color: 'tan'});
// -> 'Row Ids for dogColors result table changed'
store.setRow('pets', 'tom', {species: 'cat', color: 'gray'});
// -> 'Row Ids for catColors result table changed'

store.delListener(listenerId);

Since

v2.0.0