useSliceIdsListener
The useSliceIdsListener
hook registers a listener function with the Indexes
object that will be called whenever the Slice
Ids
in an Index
change.
useSliceIdsListener(
indexId: IdOrNull,
listener: SliceIdsListener,
listenerDeps?: DependencyList,
indexesOrIndexesId?: IndexesOrIndexesId,
): void
Type | Description | |
---|---|---|
indexId | IdOrNull | |
listener | SliceIdsListener | 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 useSliceIds
hook).
You can either listen to a single Index
(by specifying the Index
Id
as the method's first parameter), or changes to any Index
(by providing a null
wildcard).
Unlike the addSliceIdsListener
method, which returns a listener Id
and requires you to remove it manually, the useSliceIdsListener
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 useSliceIdsListener
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 {Provider, useSliceIdsListener} from 'tinybase/ui-react';
import {createIndexes, createStore} from 'tinybase';
import React from 'react';
import {createRoot} from 'react-dom/client';
const App = ({indexes}) => (
<Provider indexes={indexes}>
<Pane />
</Provider>
);
const Pane = () => {
useSliceIdsListener('bySpecies', () => console.log('Slice 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().sliceIds);
// -> 1
store.setRow('pets', 'lowly', {species: 'worm'});
// -> 'Slice Ids changed'
root.unmount();
console.log(indexes.getListenerStats().sliceIds);
// -> 0
Since
v1.0.0