TinyBase logoTinyBase

Param

The Param type describes a function that takes a param Id and returns its value within a parameterized query.

(paramId: Id): ParamValue | undefined
TypeDescription
paramIdId

The Id of the param to fetch the value for.

returnsParamValue | undefined

A Cell value or undefined if the param is not set.

A Param function is provided when setting parameterized query definitions, and allows you to reference dynamic param values that can be updated without redefining the entire query. Param values can be primitives (string, number, boolean, null) or arrays of those types.

Examples

This example shows a query that uses a param to filter results.

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);
queries.setQueryDefinition(
  'query',
  'pets',
  ({select, where, param}) => {
    select('color');
    where('species', param('species'));
  },
  {species: 'dog'},
);

console.log(queries.getResultTable('query'));
// -> {fido: {color: 'brown'}, cujo: {color: 'black'}}

queries.setParamValue('query', 'species', 'cat');
console.log(queries.getResultTable('query'));
// -> {felix: {color: 'black'}}

This example shows a query that uses an array param to filter by multiple values.

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'},
  rex: {species: 'dog', color: 'gold'},
});

const queries = createQueries(store);
queries.setQueryDefinition(
  'query',
  'pets',
  ({select, where, param}) => {
    select('species');
    where((getTableCell) =>
      (param('colors') as string[])?.includes(getTableCell('color')),
    );
  },
  {colors: ['brown', 'gold']},
);

console.log(queries.getResultTable('query'));
// -> {fido: {species: 'dog'}, rex: {species: 'dog'}}

queries.setParamValue('query', 'colors', ['black']);
console.log(queries.getResultTable('query'));
// -> {felix: {species: 'cat'}, cujo: {species: 'dog'}}

Since

v7.2.0