TinyBase logoTinyBase

usePersisterOrPersisterById

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

usePersisterOrPersisterById(persisterOrPersisterId?: PersisterOrPersisterId): AnyPersister | undefined
TypeDescription
persisterOrPersisterId?PersisterOrPersisterId

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

returnsAnyPersister | undefined

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

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

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

Example

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

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

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

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

Since

v5.3.0