useLinkedRowIdsListener
The useLinkedRowIdsListener
hook registers a listener function with the Relationships
object that will be called whenever the linked Row
Ids
in a Relationship
change.
useLinkedRowIdsListener(
relationshipId: string,
firstRowId: string,
listener: LinkedRowIdsListener,
listenerDeps?: DependencyList,
relationshipsOrRelationshipsId?: RelationshipsOrRelationshipsId,
): void
Type | Description | |
---|---|---|
relationshipId | string | The |
firstRowId | string | |
listener | LinkedRowIdsListener | The function that will be called whenever the linked |
listenerDeps? | DependencyList | An optional array of dependencies for the |
relationshipsOrRelationshipsId? | RelationshipsOrRelationshipsId | The |
returns | void | This has no return value. |
This hook is useful for situations where a component needs to register its own specific listener to do more than simply tracking the value (which is more easily done with the useLinkedRowsId hook).
Unlike other listener registration methods, you cannot provide null
wildcards for the first two parameters of the useLinkedRowIdsListener method. This prevents the prohibitive expense of tracking all the possible linked lists (and partial linked lists within them) in a Store
.
Unlike the addLinkedRowsIdListener method, which returns a listener Id
and requires you to remove it manually, the useLinkedRowIdsListener
hook manages this lifecycle for you: when the listener changes (per its listenerDeps
dependencies) or the component unmounts, the listener on the underlying Indexes
object will be deleted.
Example
This example uses the useLinkedRowIdsListener
hook to create a listener that is scoped to a single component. When the component is unmounted, the listener is removed from the Relationships
object.
import {Provider, useLinkedRowIdsListener} 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 = () => {
useLinkedRowIdsListener('petSequence', 'fido', () =>
console.log('Linked Row Ids changed'),
);
return <span>App</span>;
};
const store = createStore().setTable('pets', {
fido: {species: 'dog', next: 'felix'},
felix: {species: 'cat', next: 'cujo'},
cujo: {species: 'dog'},
});
const relationships = createRelationships(store);
relationships.setRelationshipDefinition(
'petSequence',
'pets',
'pets',
'next',
);
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App relationships={relationships} />);
console.log(relationships.getListenerStats().linkedRowIds);
// -> 1
store.setRow('pets', 'toto', {species: 'dog'});
store.setCell('pets', 'cujo', 'next', 'toto');
// -> 'Linked Row Ids changed'
root.unmount();
console.log(relationships.getListenerStats().linkedRowIds);
// -> 0
Since
v1.0.0