TinyBase logoTinyBase

useRelationshipIds

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

useRelationshipIds(relationshipsOrRelationshipsId?: RelationshipsOrRelationshipsId): Ids
TypeDescription
relationshipsOrRelationshipsId?RelationshipsOrRelationshipsId

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

returnsIds

The Relationship Ids in the Relationships 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 Relationships object or a set of Relationships objects named by Id. The useRelationshipIds hook lets you indicate which Relationships object to get data for: omit the optional final parameter for the default context Relationships object, provide an Id for a named context Relationships object, or provide a Relationships object explicitly by reference.

When first rendered, this hook will create a listener so that changes to the Relationship Ids in the Relationships 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 Relationships object outside the application, which is used in the useRelationshipIds hook by reference. A newly-registered Relationship re-renders the component.

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

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

const addRelationshipDefinition = () =>
  relationships.setRelationshipDefinition(
    'petSpecies',
    'pets',
    'species',
    'species',
  );
addRelationshipDefinition();
console.log(app.innerHTML);
// -> '<span>["petSpecies"]</span>'

Since

v4.1.0