TinyBase logoTinyBase β

useIndexesOrIndexesById

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

useIndexesOrIndexesById(indexesOrIndexesId?: IndexesOrIndexesId): Indexes | undefined
TypeDescription
indexesOrIndexesId?IndexesOrIndexesId

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

returnsIndexes | undefined

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

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

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

Example

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

import {Provider, useIndexesOrIndexesById} from 'tinybase/ui-react';
import {createIndexes, createStore} from 'tinybase';
import React from 'react';
import {createRoot} from 'react-dom/client';

const App = ({indexes}) => (
  <Provider indexes={indexes}>
    <Pane />
  </Provider>
);
const Pane = ({indexes}) => (
  <span>
    {JSON.stringify(useIndexesOrIndexesById(indexes).getIndexIds())}
  </span>
);

const indexes = createIndexes(
  createStore().setTable('pets', {
    fido: {species: 'dog'},
    felix: {species: 'cat'},
    cujo: {species: 'dog'},
  }),
).setIndexDefinition('bySpecies', 'pets', 'species');

const app = document.createElement('div');
const root = createRoot(app);
root.render(<App indexes={indexes} />);
console.log(app.innerHTML);
// -> '<span>["bySpecies"]</span>'

Since

v4.1.0