TinyBase logoTinyBase β

getMetric

The getMetric function returns a reactive object reflecting the value of a named Metric in a Metrics object, and registers a listener so that any changes to that Metric will update current.

getMetric(
  metricId: MaybeGetter<string>,
  metricsOrMetricsId?: MaybeGetter<undefined | MetricsOrMetricsId>,
): {current: number | undefined}
TypeDescription
metricIdMaybeGetter<string>

The Id of the Metric (or a getter returning it).

metricsOrMetricsId?MaybeGetter<undefined | MetricsOrMetricsId>

The Metrics object to use (plain or getter), or its Id.

returns{current: number | undefined}

A reactive object with a current number | undefined property.

Example

This example passes a TinyBase object into a Svelte component and reads the reactive object's current property.

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

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

  let {metrics} = $props();

  const result = getMetric('speciesPrice', metrics);
</script>

{result.current}
import {flushSync, mount} from 'svelte';
import {createMetrics, 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 metrics = createMetrics(store).setMetricDefinition(
  'speciesPrice',
  'species',
  'sum',
  'price',
);
const app = document.body.appendChild(document.createElement('div'));
flushSync(() => mount(App, {target: app, props: {metrics}}));
console.log(app.textContent);
// -> '9'

Since

v8.1.0