TinyBase logoTinyBase β

useRelationshipsOrRelationshipsById

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

useRelationshipsOrRelationshipsById(relationshipsOrRelationshipsId?: RelationshipsOrRelationshipsId): Relationships | undefined
TypeDescription
relationshipsOrRelationshipsId?RelationshipsOrRelationshipsId

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

returnsRelationships | undefined

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

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

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

Example

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

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

const App = ({relationships}) => (
  <Provider relationships={relationships}>
    <Pane />
  </Provider>
);
const Pane = ({relationships}) => (
  <span>
    {JSON.stringify(
      useRelationshipsOrRelationshipsById(
        relationships,
      ).getRelationshipIds(),
    )}
  </span>
);

const relationships = createRelationships(
  createStore()
    .setTable('pets', {fido: {species: 'dog'}, cujo: {species: 'dog'}})
    .setTable('species', {wolf: {price: 10}, dog: {price: 5}}),
).setRelationshipDefinition('petSpecies', 'pets', 'species', 'species');

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

Since

v4.1.0