TinyBase logoTinyBase

useMetricIds

The useMetricIds hook gets an array of the Metric Ids registered with a Metrics object, and registers a listener so that any changes to that result will cause a re-render.

useMetricIds(metricsOrMetricsId?: MetricsOrMetricsId): Ids
TypeDescription
metricsOrMetricsId?MetricsOrMetricsId

The Metrics object to be accessed: omit for the default context Metrics object, provide an Id for a named context Metrics object, or provide an explicit reference.

returnsIds

The Metric Ids in the Metrics object, or an empty array.

A Provider component is used to wrap part of an application in a context, and it can contain a default Metrics object or a set of Metrics objects named by Id. The useMetricIds hook lets you indicate which Metrics object to get data for: omit the optional final parameter for the default context Metrics object, provide an Id for a named context Metrics object, or provide a Metrics object explicitly by reference.

When first rendered, this hook will create a listener so that changes to the Metric Ids in the Metrics object will cause a re-render. When the component containing this hook is unmounted, the listener will be automatically removed.

Example

This example creates an Metrics object outside the application, which is used in the useMetricIds hook by reference. A newly-registered Metric re-renders the component.

import {createMetrics, createStore} from 'tinybase';
import React from 'react';
import {createRoot} from 'react-dom/client';
import {useMetricIds} from 'tinybase/ui-react';

const store = createStore().setTable('pets', {
  fido: {species: 'dog'},
  felix: {species: 'cat'},
  cujo: {species: 'dog'},
});
const metrics = createMetrics(store);
const App = () => <span>{JSON.stringify(useMetricIds(metrics))}</span>;

const app = document.createElement('div');
createRoot(app).render(<App />);
console.log(app.innerHTML);
// -> '<span>[]</span>'

const addMetricDefinition = () =>
  metrics.setMetricDefinition('highestPrice', 'species', 'max', 'price');
addMetricDefinition();
console.log(app.innerHTML);
// -> '<span>["highestPrice"]</span>'

Since

v4.1.0