useProvideIndexes
The useProvideIndexes
hook is used to add an Indexes
object by Id
to a Provider
component, but imperatively from a component within it.
useProvideIndexes(
indexesId: string,
indexes: Indexes,
): void
Type | Description | |
---|---|---|
indexesId | string | The |
indexes | Indexes | The |
returns | void | This has no return value. |
Normally you will register an Indexes
object by Id
in a context by using the indexesById
prop of the top-level Provider
component. This hook, however, lets you dynamically add a new Indexes
object to the context, from within a descendent component. This is useful for applications where the set of Indexes
objects is not known at the time of the first render of the root Provider.
A Indexes
object added to the Provider context in this way will be available to other components within the context (using the useIndexes
hook and so on). If you use the same Id
as an existing Indexes
object registration, the new one will take priority over one provided by the indexesById
prop.
Note that other components that consume an Indexes
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 useIndexes('petIndexes')?
to do this.
Example
This example creates a Provider context. A child component registers an Indexes
object into it which is then consumable by a peer child component.
import React from 'react';
import {createRoot} from 'react-dom/client';
import {createIndexes, createStore} from 'tinybase';
import {
Provider,
useCreateIndexes,
useCreateStore,
useIndexes,
useProvideIndexes,
} from 'tinybase/ui-react';
const App = () => (
<Provider>
<RegisterIndexes />
<ConsumeIndexes />
</Provider>
);
const RegisterIndexes = () => {
const store = useCreateStore(() =>
createStore().setCell('pets', 'fido', 'color', 'brown'),
);
const indexes = useCreateIndexes(store, (store) =>
createIndexes(store).setIndexDefinition(
'petsByColor',
'pets',
'color',
),
);
useProvideIndexes('petIndexes', indexes);
return null;
};
const ConsumeIndexes = () => (
<span>
{JSON.stringify(useIndexes('petIndexes')?.getSliceIds('petsByColor'))}
</span>
);
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App />);
console.log(app.innerHTML);
// -> '<span>["brown"]</span>'
Since
v5.3.0