TinyBase logoTinyBase

useIndexIds

The useIndexIds hook gets an array of the Index Ids registered with an Indexes object, and registers a listener so that any changes to that result will cause a re-render.

useIndexIds(indexesOrIndexesId?: IndexesOrIndexesId): Ids
TypeDescription
indexesOrIndexesId?IndexesOrIndexesId

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

returnsIds

The Index Ids in the Indexes object, or an empty array.

A Provider component is used to wrap part of an application in a context, and it can contain a default Indexes object or a set of Indexes objects named by Id. The useIndexIds hook lets you indicate which Indexes object to get data for: omit the optional final parameter for the default context Indexes object, provide an Id for a named context Indexes object, or provide an Indexes object explicitly by reference.

When first rendered, this hook will create a listener so that changes to the Index Ids in the Indexes object will cause a re-render. When the component containing this hook is unmounted, the listener will be automatically removed.

Example

This example creates an Indexes object outside the application, which is used in the useIndexIds hook by reference. A newly-registered Index re-renders the component.

const store = createStore().setTable('pets', {
  fido: {species: 'dog'},
  felix: {species: 'cat'},
  cujo: {species: 'dog'},
});
const indexes = createIndexes(store);
const App = () => <span>{JSON.stringify(useIndexIds(indexes))}</span>;

const app = document.createElement('div');
ReactDOMClient.createRoot(app).render(<App />);
console.log(app.innerHTML);
// -> '<span>[]</span>'

indexes.setIndexDefinition('bySpecies', 'pets', 'species');
console.log(app.innerHTML);
// -> '<span>["bySpecies"]</span>'

Since

v4.1.0