useSliceRowIdsListener
The useSliceRowIdsListener hook registers a listener function with the Indexes object that will be called whenever the Row Ids in a Slice change.
useSliceRowIdsListener(
indexId: IdOrNull,
sliceId: IdOrNull,
listener: SliceRowIdsListener,
listenerDeps?: DependencyList,
indexesOrIndexesId?: IndexesOrIndexesId,
): void| Type | Description | |
|---|---|---|
indexId | IdOrNull | |
sliceId | IdOrNull | |
listener | SliceRowIdsListener | The function that will be called whenever the |
listenerDeps? | DependencyList | An optional array of dependencies for the |
indexesOrIndexesId? | IndexesOrIndexesId | 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 useSliceRowIds hook).
You can either listen to a single Slice (by specifying the Index Id and Slice Id as the method's first two parameters), or changes to any Slice (by providing null wildcards).
Both, either, or neither of the indexId and sliceId parameters can be wildcarded with null. You can listen to a specific Slice in a specific Index, any Slice in a specific Index, a specific Slice in any Index, or any Slice in any Index.
Unlike the addSliceRowIdsListener method, which returns a listener Id and requires you to remove it manually, the useSliceRowIdsListener 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 useSliceRowIdsListener hook to create a listener that is scoped to a single component. When the component is unmounted, the listener is removed from the Indexes object.
import React from 'react';
import {createRoot} from 'react-dom/client';
import {createIndexes, createStore} from 'tinybase';
import {Provider, useSliceRowIdsListener} from 'tinybase/ui-react';
const App = ({indexes}) => (
<Provider indexes={indexes}>
<Pane />
</Provider>
);
const Pane = () => {
useSliceRowIdsListener('bySpecies', 'dog', () =>
console.log('Slice Row Ids changed'),
);
return <span>App</span>;
};
const store = createStore().setTable('pets', {
fido: {species: 'dog'},
felix: {species: 'cat'},
cujo: {species: 'dog'},
});
const indexes = createIndexes(store);
indexes.setIndexDefinition('bySpecies', 'pets', 'species');
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App indexes={indexes} />);
console.log(indexes.getListenerStats().sliceRowIds);
// -> 1
store.setRow('pets', 'toto', {species: 'dog'});
// -> 'Slice Row Ids changed'
root.unmount();
console.log(indexes.getListenerStats().sliceRowIds);
// -> 0
Since
v1.0.0