TinyBase logoTinyBase β

usePersisterStatusListener

The usePersisterStatusListener hook registers a listener function with the Persister that will be called when its status changes.

usePersisterStatusListener(
  listener: StatusListener<StoreOrMergeableStore>,
  listenerDeps?: DependencyList,
  persisterOrPersisterId?: PersisterOrPersisterId,
): void
TypeDescription
listenerStatusListener<StoreOrMergeableStore>

The function that will be called whenever the status of the Persister changes.

listenerDeps?DependencyList

An optional array of dependencies for the listener function, which, if any change, result in the re-registration of the listener. This parameter defaults to an empty array.

persisterOrPersisterId?PersisterOrPersisterId

The Persister to be accessed: omit for the default context Persister, provide an Id for a named context Persister, or provide an explicit reference.

returnsvoid

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 usePersisterStatus hook).

Unlike the addStatusListener method, which returns a listener Id and requires you to remove it manually, the usePersisterStatusListener hook manages this lifecycle for you: when the listener changes (per its listenerDeps dependencies) or the component unmounts, the listener on the underlying Persister will be deleted.

Example

This example uses the usePersisterStatusListener hook to create a listener that is scoped to a single component. When the component is unmounted, the listener is removed from the Persister.

import {Provider, usePersisterStatusListener} from 'tinybase/ui-react';
import React from 'react';
import {createRoot} from 'react-dom/client';
import {createSessionPersister} from 'tinybase/persisters/persister-browser';
import {createStore} from 'tinybase';

const App = ({persister}) => (
  <Provider persister={persister}>
    <Pane />
  </Provider>
);
const Pane = () => {
  usePersisterStatusListener((persister, status) =>
    console.log('Persister status changed: ' + status),
  );
  return <span>App</span>;
};

const persister = createSessionPersister(createStore(), 'pets');
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App persister={persister} />);

persister.load();
// -> 'Persister status changed: 1'
// ...
// -> 'Persister status changed: 0'

persister.save();
// -> 'Persister status changed: 2'
// ...
// -> 'Persister status changed: 0'

Since

v5.3.0