TinyBase logoTinyBase

useRelationships

The useRelationships hook is used to get a reference to a Relationships object from within a Provider component context.

useRelationships(id?: string): Relationships | undefined
TypeDescription
id?string

An optional Id for accessing a Relationships object that was named with an Id in the Provider.

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).

A Provider component is used to wrap part of an application in a context. It can contain a default Relationships object (or a set of Relationships objects named by Id) that can be easily accessed without having to be passed down as props through every component.

The useRelationships hook lets you either get a reference to the default Relationships object (when called without a parameter), or one of the Relationships objects that are named by Id (when called with an Id parameter).

Examples

This example creates a Provider context into which a default Relationships object is provided. A component within it then uses the useRelationships hook to get a reference to the Relationships object again, without the need to have it passed as a prop.

import {Provider, useRelationships} 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 = () => (
  <span>{useRelationships().getListenerStats().remoteRowId}</span>
);

const relationships = createRelationships(createStore());
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App relationships={relationships} />);
console.log(app.innerHTML);
// -> '<span>0</span>'

This example creates a Provider context into which a Relationships object is provided, named by Id. A component within it then uses the useRelationships hook with that Id to get a reference to the Relationships object again, without the need to have it passed as a prop.

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

const App = ({relationships}) => (
  <Provider relationshipsById={{petStore: relationships}}>
    <Pane />
  </Provider>
);
const Pane = () => (
  <span>
    {useRelationships('petStore').getListenerStats().remoteRowId}
  </span>
);

const relationships = createRelationships(createStore());
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App relationships={relationships} />);
console.log(app.innerHTML);
// -> '<span>0</span>'

Since

v1.0.0