TinyBase logoTinyBase

useSynchronizerOrSynchronizerById

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

useSynchronizerOrSynchronizerById(synchronizerOrSynchronizerId?: SynchronizerOrSynchronizerId): Synchronizer | undefined
TypeDescription
synchronizerOrSynchronizerId?SynchronizerOrSynchronizerId

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

returnsSynchronizer | undefined

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

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

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

Example

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

import {
  Provider,
  useSynchronizerOrSynchronizerById,
} from 'tinybase/ui-react';
import React from 'react';
import {createLocalSynchronizer} from 'tinybase/synchronizers/synchronizer-local';
import {createMergeableStore} from 'tinybase';
import {createRoot} from 'react-dom/client';

const App = ({synchronizer}) => (
  <Provider synchronizer={synchronizer}>
    <Pane />
  </Provider>
);
const Pane = ({synchronizer}) => (
  <span>
    {useSynchronizerOrSynchronizerById(synchronizer).getStatus()}
  </span>
);

const synchronizer = createLocalSynchronizer(createMergeableStore());
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App synchronizer={synchronizer} />);
console.log(app.innerHTML);
// -> '<span>0</span>'

Since

v5.3.0