TinyBase logoTinyBase

useProvideRelationships

The useProvideRelationships hook is used to add a Relationships object by Id to a Provider component, but imperatively from a component within it.

useProvideRelationships(
  relationshipsId: string,
  relationships: Relationships,
): void
TypeDescription
relationshipsIdstring

The Id of the Relationships object to be registered with the Provider.

relationshipsRelationships

The Relationships object to be registered.

returnsvoid

This has no return value.

Normally you will register a Relationships object by Id in a context by using the relationshipsById prop of the top-level Provider component. This hook, however, lets you dynamically add a new Relationships object to the context, from within a component. This is useful for applications where the set of Relationships objects is not known at the time of the first render of the root Provider.

A Relationships object added to the Provider context in this way will be available to other components within the context (using the useRelationships hook and so on). If you use the same Id as an existing Relationships object registration, the new one will take priority over one provided by the relationshipsById prop.

Note that other components that consume a Relationships 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 useRelationships('petRelationships')? to do this.

Example

This example creates a Provider context. A child component registers a Relationships object into it which is then consumable by a peer child component.

import React from 'react';
import {createRoot} from 'react-dom/client';
import {createRelationships, createStore} from 'tinybase';
import {
  Provider,
  useCreateRelationships,
  useCreateStore,
  useProvideRelationships,
  useRelationships,
} from 'tinybase/ui-react';

const App = () => (
  <Provider>
    <RegisterRelationships />
    <ConsumeRelationships />
  </Provider>
);
const RegisterRelationships = () => {
  const store = useCreateStore(() =>
    createStore()
      .setTable('pets', {fido: {species: 'dog'}})
      .setTable('species', {dog: {price: 5}}),
  );
  const relationships = useCreateRelationships(store, (store) =>
    createRelationships(store).setRelationshipDefinition(
      'petSpecies',
      'pets',
      'species',
      'species',
    ),
  );
  useProvideRelationships('petRelationships', relationships);
  return null;
};
const ConsumeRelationships = () => (
  <span>
    {useRelationships('petRelationships')?.getRemoteRowId(
      'petSpecies',
      'fido',
    )}
  </span>
);

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

Since

v5.3.0