TinyBase logoTinyBase

addParamValuesListener

The addParamValuesListener method registers a listener function with the Queries object that will be called whenever the param values of a query change.

addParamValuesListener(
  queryId: IdOrNull,
  listener: ParamValuesListener,
): string
TypeDescription
queryIdIdOrNull

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

listenerParamValuesListener

The function that will be called whenever the param values of the query change.

returnsstring

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

The provided listener is a ParamValuesListener function, and will be called with a reference to the Queries object, the Id of the query whose param values changed, and an object containing the new param values.

Example

This example registers two listeners that respond to changes to the param values of a specific query, or any query respectively.

import {createQueries, createStore} from 'tinybase';

const store = createStore().setTable('pets', {
  // store data
});

const queries = createQueries(store).setQueryDefinition(
  'petsByColor',
  'pets',
  () => {
    // query definition
  },
  {color: 'white'},
);

const listenerId1 = queries.addParamValuesListener(
  'petsByColor',
  (queries, queryId, paramValues) => {
    console.log(
      `Params for specific query changed: ${JSON.stringify(paramValues)}`,
    );
  },
);
const listenerId2 = queries.addParamValuesListener(
  null,
  (queries, queryId, paramValues) => {
    console.log(
      `Params for "${queryId}" changed: ${JSON.stringify(paramValues)}`,
    );
  },
);

queries.setParamValues('petsByColor', {color: 'black'});
// -> 'Params for specific query changed: {"color":"black"}'
// -> 'Params for "petsByColor" changed: {"color":"black"}'
queries.setParamValues('petsByColor', {color: 'brown'});
// -> 'Params for specific query changed: {"color":"brown"}'
// -> 'Params for "petsByColor" changed: {"color":"brown"}'

queries.delListener(listenerId1);
queries.delListener(listenerId2);

Since

v7.2.0