useSynchronizer
The useSynchronizer hook is used to get a reference to a Synchronizer object from within a Provider component context.
useSynchronizer(id?: string): Synchronizer | undefined| Type | Description | |
|---|---|---|
id? | string | An optional |
| returns | Synchronizer | undefined | A reference to the |
A Provider component is used to wrap part of an application in a context. It can contain a default Synchronizer object (or a set of Synchronizer objects named by Id) that can be easily accessed without having to be passed down as props through every component.
The useSynchronizer hook lets you either get a reference to the default Synchronizer object (when called without a parameter), or one of the Synchronizer objects that are named by Id (when called with an Id parameter).
Examples
This example creates a Provider context into which a default Synchronizer object is provided. A component within it then uses the useSynchronizer hook to get a reference to the Synchronizer object again, without the need to have it passed as a prop.
import React from 'react';
import {createRoot} from 'react-dom/client';
import {createMergeableStore} from 'tinybase';
import {createLocalSynchronizer} from 'tinybase/synchronizers/synchronizer-local';
import {Provider, useSynchronizer} from 'tinybase/ui-react';
const App = ({synchronizer}) => (
<Provider synchronizer={synchronizer}>
<Pane />
</Provider>
);
const Pane = () => <span>{useSynchronizer().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>'
This example creates a Provider context into which a Synchronizer object is provided, named by Id. A component within it then uses the useSynchronizer hook with that Id to get a reference to the Synchronizer object again, without the need to have it passed as a prop.
import React from 'react';
import {createRoot} from 'react-dom/client';
import {createMergeableStore} from 'tinybase';
import {createLocalSynchronizer} from 'tinybase/synchronizers/synchronizer-local';
import {Provider, useSynchronizer} from 'tinybase/ui-react';
const App = ({synchronizer}) => (
<Provider synchronizersById={{petSynchronizer: synchronizer}}>
<Pane />
</Provider>
);
const Pane = () => (
<span>{useSynchronizer('petSynchronizer').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