TinyBase logoTinyBase

addValuesListener

The addValuesListener method registers a listener function with the Store that will be called whenever the Values change.

addValuesListener(
  listener: ValuesListener<Store>,
  mutator?: boolean,
): string
TypeDescription
listenerValuesListener<Store>

The function that will be called whenever data in the Values 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 ValuesListener function, and will be called with a reference to the Store and a GetValueChange 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 Store's Values.

import {createStore} from 'tinybase';

const store = createStore().setValues({open: true, employees: 3});
const listenerId = store.addValuesListener((store, getValueChange) => {
  console.log('values changed');
  console.log(getValueChange('employees'));
});

store.setValue('employees', 4);
// -> 'values changed'
// -> [true, 3, 4]

store.delListener(listenerId);

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

import {createStore} from 'tinybase';

const store = createStore().setValues({open: true, employees: 3});
const listenerId = store.addValuesListener(
  (store) => store.setValue('updated', true),
  true,
);

store.setValue('employees', 4);
console.log(store.getValues());
// -> {open: true, employees: 4, updated: true}

store.delListener(listenerId);

Since

v3.0.0