TinyBase logoTinyBase

useProvideMetrics

The useProvideMetrics hook is used to add a Metrics object by Id to a Provider component, but imperatively from a component within it.

useProvideMetrics(
  metricsId: string,
  metrics: Metrics,
): void
TypeDescription
metricsIdstring

The Id of the Metrics object to be registered with the Provider.

metricsMetrics

The Metrics object to be registered.

returnsvoid

This has no return value.

Normally you will register a Metrics object by Id in a context by using the metricsById prop of the top-level Provider component. This hook, however, lets you dynamically add a new Metrics object to the context, from within a descendent component. This is useful for applications where the set of Metrics objects is not known at the time of the first render of the root Provider.

A Metrics object added to the Provider context in this way will be available to other components within the context (using the useMetrics hook and so on). If you use the same Id as an existing Metrics object registration, the new one will take priority over one provided by the metricsById prop.

Note that other components that consume a Metrics object registered like this should defend against it being undefined at first. On the first render, the other component will likely not yet have completed the registration. In the example below, we use the null-safe useMetrics('petMetrics')? to do this.

Example

This example creates a Provider context. A child component registers a Metrics object into it which is then consumable by a peer child component.

import {
  Provider,
  useCreateMetrics,
  useCreateStore,
  useMetrics,
  useProvideMetrics,
} from 'tinybase/ui-react';
import {createMetrics, createStore} from 'tinybase';
import React from 'react';
import {createRoot} from 'react-dom/client';

const App = () => (
  <Provider>
    <RegisterMetrics />
    <ConsumeMetrics />
  </Provider>
);
const RegisterMetrics = () => {
  const store = useCreateStore(() =>
    createStore().setCell('pets', 'fido', 'color', 'brown'),
  );
  const metrics = useCreateMetrics(store, (store) =>
    createMetrics(store).setMetricDefinition('petCount', 'pets', 'count'),
  );
  useProvideMetrics('petMetrics', metrics);
  return null;
};
const ConsumeMetrics = () => (
  <span>{useMetrics('petMetrics')?.getMetric('petCount')}</span>
);

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

Since

v5.3.0