TinyBase logoTinyBase

useMetricsOrMetricsById

The useMetricsOrMetricsById hook is used to get a reference to a Metrics object from within a Provider component context, or have it passed directly to this hook.

useMetricsOrMetricsById(metricsOrMetricsId?: MetricsOrMetricsId): Metrics | undefined
TypeDescription
metricsOrMetricsId?MetricsOrMetricsId

Either an Id for accessing a Metrics object that was named with an Id in the Provider, or the Metrics object itself.

returnsMetrics | undefined

A reference to the Metrics object (or undefined if not within a Provider context, or if the requested Metrics object does not exist).

This is mostly of use when you are developing a component that needs a Metrics object and which might have been passed in explicitly to the component or is to be picked up from the context by Id (a common pattern for Metrics-based components).

This hook is unlikely to be used often. For most situations, you will want to use the useMetrics hook.

Example

This example creates a Provider context into which a default Metrics object is provided. A component within it then uses the useMetricsOrMetricsById hook to get a reference to the Metrics object again, without the need to have it passed as a prop. Note however, that unlike the useMetrics hook example, this component would also work if you were to pass the Metrics object directly into it, making it more portable.

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

const App = ({metrics}) => (
  <Provider metrics={metrics}>
    <Pane />
  </Provider>
);
const Pane = ({metrics}) => (
  <span>
    {JSON.stringify(useMetricsOrMetricsById(metrics).getMetricIds())}
  </span>
);

const metrics = createMetrics(
  createStore().setTable('species', {
    dog: {price: 5},
    cat: {price: 4},
    worm: {price: 1},
  }),
).setMetricDefinition('highestPrice', 'species', 'max', 'price');

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

Since

v4.1.0