TinyBase logoTinyBase

useQueryIds

The useQueryIds hook gets an array of the Query Ids registered with a Queries object, and registers a listener so that any changes to that result will cause a re-render.

useQueryIds(queriesOrQueriesId?: QueriesOrQueriesId): Ids
TypeDescription
queriesOrQueriesId?QueriesOrQueriesId

The Queries object to be accessed: omit for the default context Queries object, provide an Id for a named context Queries object, or provide an explicit reference.

returnsIds

The Query Ids in the Queries object, or an empty array.

A Provider component is used to wrap part of an application in a context, and it can contain a default Queries object or a set of Queries objects named by Id. The useQueryIds hook lets you indicate which Queries object to get data for: omit the optional final parameter for the default context Queries object, provide an Id for a named context Queries object, or provide a Queries object explicitly by reference.

When first rendered, this hook will create a listener so that changes to the Query Ids in the Queries object will cause a re-render. When the component containing this hook is unmounted, the listener will be automatically removed.

Example

This example creates an Queries object outside the application, which is used in the useQueryIds hook by reference. A newly-registered Relationship re-renders the component.

import {createQueries, createStore} from 'tinybase';
import React from 'react';
import {createRoot} from 'react-dom/client';
import {useQueryIds} from 'tinybase/ui-react';

const store = createStore().setTable('pets', {
  fido: {species: 'dog'},
  felix: {species: 'cat'},
  cujo: {species: 'dog'},
});
const queries = createQueries(store);
const App = () => <span>{JSON.stringify(useQueryIds(queries))}</span>;

const app = document.createElement('div');
createRoot(app).render(<App />);
console.log(app.innerHTML);
// -> '<span>[]</span>'

const addQueryDefinition = () =>
  queries.setQueryDefinition('dogColors', 'pets', ({select, where}) => {
    select('color');
    where('species', 'dog');
  });
addQueryDefinition();
console.log(app.innerHTML);
// -> '<span>["dogColors"]</span>'

Since

v4.1.0