TinyBase logoTinyBase β

onValue

The onValue function registers a listener that is called whenever the value of a specified Value changes.

onValue(
  valueId: MaybeGetter<IdOrNull>,
  listener: ValueListener,
  mutator?: boolean,
  storeOrStoreId?: MaybeGetter<undefined | StoreOrStoreId>,
): void
TypeDescription
valueIdMaybeGetter<IdOrNull>

The Id of the Value to listen to, or null to listen to any Value.

listenerValueListener

The function to call when the Value changes.

mutator?boolean

An optional boolean indicating the listener mutates Store data.

storeOrStoreId?MaybeGetter<undefined | StoreOrStoreId>

The Store to use, or its Id.

returnsvoid

This has no return value.

Example

This example registers a Svelte listener and responds to a TinyBase change.

App.svelte
<svelte:options runes={true} />

<script>
  import {onValue} from 'tinybase/ui-svelte';

  let {store} = $props();
  let seen = $state('');

  onValue('open', () => (seen = 'changed'), false, store);
</script>

{seen}
import {flushSync, mount} from 'svelte';
import {createStore} from 'tinybase';
import App from './App.svelte';

const store = createStore()
  .setTables({
    pets: {
      fido: {species: 'dog', color: 'brown', sold: false, next: 'felix'},
      felix: {species: 'cat', color: 'black', sold: true},
    },
    species: {dog: {price: 5}, cat: {price: 4}},
  })
  .setValues({open: true, employees: 3});
const app = document.body.appendChild(document.createElement('div'));
flushSync(() => mount(App, {target: app, props: {store}}));
flushSync(() => {
  store.setValue('open', false);
});
flushSync();
console.log(app.textContent);
// -> 'changed'

Since

v8.1.0