TinyBase logoTinyBase

useProvideCheckpoints

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

useProvideCheckpoints(
  checkpointsId: string,
  checkpoints: Checkpoints,
): void
TypeDescription
checkpointsIdstring

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

checkpointsCheckpoints

The Checkpoints object to be registered.

returnsvoid

This has no return value.

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

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

Note that other components that consume a Checkpoints 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 useCheckpoints('petCheckpoints')? to do this.

Example

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

import React from 'react';
import {createRoot} from 'react-dom/client';
import {createCheckpoints, createStore} from 'tinybase';
import {
  Provider,
  useCheckpoints,
  useCreateCheckpoints,
  useCreateStore,
  useProvideCheckpoints,
} from 'tinybase/ui-react';

const App = () => (
  <Provider>
    <RegisterCheckpoints />
    <ConsumeCheckpoints />
  </Provider>
);
const RegisterCheckpoints = () => {
  const store = useCreateStore(() =>
    createStore().setCell('pets', 'fido', 'color', 'brown'),
  );
  const checkpoints = useCreateCheckpoints(store, createCheckpoints);
  useProvideCheckpoints('petCheckpoints', checkpoints);
  return null;
};
const ConsumeCheckpoints = () => (
  <span>
    {JSON.stringify(useCheckpoints('petCheckpoints')?.getCheckpointIds())}
  </span>
);

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

Since

v5.3.0