TinyBase logoTinyBase

useCheckpointsOrCheckpointsById

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

useCheckpointsOrCheckpointsById(checkpointsOrCheckpointsId?: CheckpointsOrCheckpointsId): Checkpoints | undefined
TypeDescription
checkpointsOrCheckpointsId?CheckpointsOrCheckpointsId

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

returnsCheckpoints | undefined

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

This is mostly of use when you are developing a component that needs a Checkpoints 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 Checkpoints-based components).

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

Example

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

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

const App = ({checkpoints}) => (
  <Provider checkpoints={checkpoints}>
    <Pane />
  </Provider>
);
const Pane = ({checkpoints}) => (
  <span>
    {JSON.stringify(
      useCheckpointsOrCheckpointsById(checkpoints).getCheckpointIds(),
    )}
  </span>
);

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

Since

v4.1.0