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.
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.
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');
ReactDOM.render(<App indexes={indexes} />, app);
console.log(indexes.getListenerStats().sliceIds);
// -> 1
store.setRow('pets', 'lowly', {species: 'worm'});
// -> 'Slice Ids changed'
ReactDOM.unmountComponentAtNode(app);
console.log(indexes.getListenerStats().sliceIds);
// -> 0