useSynchronizerStatusListener
The useSynchronizerStatusListener
hook registers a listener function with the Synchronizer
that will be called when its status changes.
useSynchronizerStatusListener(
listener: StatusListener<MergeableStoreOnly>,
listenerDeps?: DependencyList,
synchronizerOrSynchronizerId?: SynchronizerOrSynchronizerId,
): void
Type | Description | |
---|---|---|
listener | StatusListener<MergeableStoreOnly> | The function that will be called whenever the status of the |
listenerDeps? | DependencyList | An optional array of dependencies for the |
synchronizerOrSynchronizerId? | SynchronizerOrSynchronizerId | The |
returns | void | This has no return value. |
This hook is useful for situations where a component needs to register its own specific listener to do more than simply tracking the value (which is more easily done with the useSynchronizerStatus
hook).
Unlike the addStatusListener
method, which returns a listener Id
and requires you to remove it manually, the useSynchronizerStatusListener
hook manages this lifecycle for you: when the listener changes (per its listenerDeps
dependencies) or the component unmounts, the listener on the underlying Synchronizer
will be deleted.
Example
This example uses the useSynchronizerStatusListener
hook to create a listener that is scoped to a single component. When the component is unmounted, the listener is removed from the Synchronizer
.
import {Provider, useSynchronizerStatusListener} 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 = () => {
useSynchronizerStatusListener((synchronizer, status) =>
console.log('Synchronizer status changed: ' + status),
);
return <span>App</span>;
};
const synchronizer = createLocalSynchronizer(createMergeableStore());
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App synchronizer={synchronizer} />);
synchronizer.load();
// -> 'Synchronizer status changed: 1'
// ...
// -> 'Synchronizer status changed: 0'
synchronizer.save();
// -> 'Synchronizer status changed: 2'
// ...
// -> 'Synchronizer status changed: 0'
Since
v5.3.0