useProvidePersister
The useProvidePersister
hook is used to add a Persister
object by Id
to a Provider
component, but imperatively from a component within it.
useProvidePersister(
persisterId: string,
persister: AnyPersister,
): void
Type | Description | |
---|---|---|
persisterId | string | The |
persister | AnyPersister | The |
returns | void | This has no return value. |
Normally you will register a Persister
object by Id
in a context by using the persistersById
prop of the top-level Provider
component. This hook, however, lets you dynamically add a new Persister
object to the context, from within a component. This is useful for applications where the set of Persister
objects is not known at the time of the first render of the root Provider.
A Persister
object added to the Provider context in this way will be available to other components within the context (using the usePersister
hook and so on). If you use the same Id
as an existing Persister
object registration, the new one will take priority over one provided by the persistersById
prop.
Note that other components that consume a Persister
object registered like this should defend against it being undefined at first. On the first render, the other component will likely not yet have completed the registration. In the example below, we use the null-safe usePersister('petPersister')?
to do this.
Example
This example creates a Provider context. A child component registers a Persister
object into it which is then consumable by a peer child component.
import React from 'react';
import {createRoot} from 'react-dom/client';
import {createStore} from 'tinybase';
import {createSessionPersister} from 'tinybase/persisters/persister-browser';
import {
Provider,
useCreatePersister,
useCreateStore,
usePersister,
useProvidePersister,
} from 'tinybase/ui-react';
const App = () => (
<Provider>
<RegisterPersister />
<ConsumePersister />
</Provider>
);
const RegisterPersister = () => {
const store = useCreateStore(() =>
createStore().setCell('pets', 'fido', 'color', 'brown'),
);
const persister = useCreatePersister(store, (store) =>
createSessionPersister(store, 'pets'),
);
useProvidePersister('petPersister', persister);
return null;
};
const ConsumePersister = () => (
<span>{usePersister('petPersister')?.getStatus()}</span>
);
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App />);
// ...
console.log(app.innerHTML);
// -> '<span>0</span>'
Since
v5.3.0